RU AdList JS Fixes

try to take over the world!

当前为 2018-12-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20181228.1
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @supportURL https://greasyfork.org/en/scripts/19993-ru-adlist-js-fixes/feedback
  8. // @match *://*/*
  9. // @exclude *://auth.wi-fi.ru/*
  10. // @exclude *://*.alfabank.ru/*
  11. // @exclude *://alfabank.ru/*
  12. // @exclude *://*.unicreditbanking.net/*
  13. // @exclude *://unicreditbanking.net/*
  14. // @exclude *://*.telegram.org/*
  15. // @exclude *://telegram.org/*
  16. // @grant unsafeWindow
  17. // @grant window.close
  18. // @run-at document-start
  19. // ==/UserScript==
  20.  
  21. (function() {
  22. 'use strict';
  23.  
  24. let win = (unsafeWindow || window);
  25.  
  26. // MooTools are crazy enough to replace standard browser object window.Document: https://mootools.net/core
  27. // Occasionally their code runs before my script on some domains and causes all kinds of havoc.
  28. let _Document = Object.getPrototypeOf(HTMLDocument.prototype);
  29. let _Element = Object.getPrototypeOf(HTMLElement.prototype);
  30. // dTree 2.05 in some cases replaces Node object
  31. let _Node = Object.getPrototypeOf(_Element);
  32. let _console = {};
  33. for (let name in win.console) _console[name] = console[name];
  34.  
  35. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  36. let isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  37. isChrome = !!window.chrome && !!window.chrome.webstore,
  38. isSafari =
  39. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  40. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || window.safari.pushNotification);
  41. let isFirefox = 'InstallTrigger' in win;
  42. let inIFrame = (win.self !== win.top);
  43. let _getAttribute = Function.prototype.call.bind(_Element.getAttribute),
  44. _setAttribute = Function.prototype.call.bind(_Element.setAttribute),
  45. _removeAttribute = Function.prototype.call.bind(_Element.removeAttribute);
  46. let _document = win.document,
  47. _de = _document.documentElement,
  48. _appendChild = _Document.appendChild.bind(_de),
  49. _removeChild = _Document.removeChild.bind(_de),
  50. _createElement = _Document.createElement.bind(_document);
  51.  
  52. if (isFirefox && // Exit on image pages in Fx
  53. _document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  54. return;
  55.  
  56. // NodeList and HTMLCollection iterator polyfill
  57. // required for old versions of Safari and Chrome 49 (last available for WinXP)
  58. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  59. if (!NodeList.prototype[Symbol.iterator])
  60. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  61. if (!HTMLCollection.prototype[Symbol.iterator])
  62. HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  63.  
  64. // Wrapper to run scripts designed to override objects available to other scripts
  65. // Required in old versions of Firefox (<58) or when running with Greasemonkey
  66. let skipLander = true;
  67. try {
  68. skipLander = !(isFirefox && ('StopIteration' in win || GM.info.scriptHandler === 'Greasemonkey'));
  69. } catch(ignore){}
  70. let batchLand = [];
  71. let batchPrepend = [];
  72. let _APIString = 'let win = window, _console = {}; for (let name in win.console) _console[name] = console[name]; '+
  73. 'let _document = win.document, _Document = Object.getPrototypeOf(HTMLDocument.prototype),'+
  74. ' _Element = Object.getPrototypeOf(HTMLElement.prototype), _Node = Object.getPrototypeOf(_Element);';
  75. let landScript = (f, pre) => {
  76. let script = _createElement('script');
  77. script.textContent = `(()=>{${_APIString}${(
  78. (pre.length > 0 ? pre.join(';') : '')
  79. )};(${f.join(')();(')})();})();`;
  80. _appendChild(script);
  81. _removeChild(script);
  82. };
  83. let scriptLander = f => f();
  84. if (!skipLander) {
  85. scriptLander = (func, ...prepend) => {
  86. prepend.forEach(
  87. x => batchPrepend.includes(x) ? null : batchPrepend.push(x)
  88. );
  89. batchLand.push(func);
  90. };
  91. _document.addEventListener(
  92. 'DOMContentLoaded', () => void (scriptLander = (f, ...prep) => landScript([f], prep)), false
  93. );
  94. }
  95.  
  96. function nullTools(opts) {
  97. let nt = this;
  98. opts = opts || {};
  99. let log = (...args) => opts.log && _console.log(...args);
  100. let warn = (...args) => _console.warn(...args);
  101. let trace = (...args) => (opts.log || opts.trace) && warn(...args);
  102.  
  103. nt.destroy = function(o, destroy) {
  104. if (!opts.destroy && !destroy && o instanceof Object)
  105. return;
  106. log('cleaning', o);
  107. try {
  108. for (let item in o) {
  109. if (item instanceof Object)
  110. nt.destroy(item);
  111. delete o[item];
  112. }
  113. } catch (e) {
  114. log('Error in object destructor', e);
  115. }
  116. };
  117.  
  118. nt.define = function(obj, prop, val, enumerable = true) {
  119. try {
  120. Object.defineProperty(
  121. obj, prop, {
  122. get: () => val,
  123. set: v => {
  124. if (v !== val) {
  125. log(`set ${prop} of`, obj, 'to', v);
  126. nt.destroy(v);
  127. }
  128. },
  129. enumerable: enumerable
  130. }
  131. );
  132. } catch (err) {
  133. _console.log(`Unable to redefine "${prop}" in `, obj, err);
  134. }
  135. };
  136. nt.proxy = function(obj, missingFuncParentName, missingFuncValue) {
  137. return new Proxy(
  138. obj, {
  139. get: (t, p) => {
  140. if (p in t)
  141. return t[p];
  142. if (typeof p === 'symbol') {
  143. t[p] = void 0;
  144. _console.warn('Missing', p, missingFuncParentName ? `in ${missingFuncParentName}` : '', '>>', t[p]);
  145. return t[p];
  146. }
  147. if (missingFuncParentName) {
  148. t[p] = nt.func(missingFuncValue, `${missingFuncParentName}.${p}`);
  149. return t[p];
  150. }
  151. _console.warn(`Missing ${p} in`, t);
  152. },
  153. set: (t, p, v) => {
  154. if (v !== t[p]) {
  155. log(`set ${p} of`, t, 'to', v);
  156. nt.destroy(v);
  157. }
  158. return true;
  159. }
  160. }
  161. );
  162. };
  163. nt.func = (val, name = '', force_log = false) => nt.proxy((...args) => {
  164. (force_log ? warn : trace)(`call ${name}(`, ...args,`) return`, val);
  165. return val;
  166. });
  167. }
  168.  
  169. // Debug function, lists all unusual window properties
  170. function getStrangeObjectsList() {
  171. _console.warn('Strangers list start');
  172. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  173. let _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  174. for (let n in win) {
  175. let val = win[n];
  176. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  177. (!(val instanceof Function) ||
  178. val instanceof Function &&
  179. !(new RegExp (`^function\\s(${n})?\\(\\)[\\s\\r\\n]*\\{[\\s\\r\\n]*\\[native\\scode\\][\\s\\r\\n]*\\}$`)).test(_toString(val))))
  180. _console.log(`${n} =`, val);
  181. }
  182. _console.warn('Strangers list end');
  183. }
  184.  
  185. // Creates and return protected style (unless protection is manually disabled).
  186. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  187. function createStyle(rules, props, skip_protect) {
  188. props = props || {};
  189. props.type = 'text/css';
  190.  
  191. function _protect(style) {
  192. if (skip_protect)
  193. return;
  194.  
  195. Object.defineProperty(style, 'sheet', {
  196. value: null,
  197. enumerable: true
  198. });
  199. Object.defineProperty(style, 'disabled', {
  200. get: () => true, //pretend to be disabled
  201. set: () => undefined,
  202. enumerable: true
  203. });
  204. (new MutationObserver(
  205. (ms) => _removeChild(ms[0].target)
  206. )).observe(style, { childList: true });
  207. }
  208.  
  209.  
  210. function _create() {
  211. let style = _appendChild(_createElement('style'));
  212. Object.assign(style, props);
  213.  
  214. function insertRules(rule) {
  215. if (rule.forEach)
  216. rule.forEach(insertRules);
  217. else try {
  218. style.sheet.insertRule(rule, 0);
  219. } catch (e) {
  220. _console.error(e);
  221. }
  222. }
  223.  
  224. insertRules(rules);
  225. _protect(style);
  226.  
  227. return style;
  228. }
  229.  
  230. let style = _create();
  231. if (skip_protect)
  232. return style;
  233.  
  234. (new MutationObserver(
  235. function(ms) {
  236. let m, node;
  237. let createStyleInANewThread = resolve => setTimeout(
  238. resolve => resolve(_create()),
  239. 0, resolve
  240. );
  241. let setStyle = st => void(style = st);
  242. for (m of ms) for (node of m.removedNodes)
  243. if (node === style)
  244. (new Promise(createStyleInANewThread))
  245. .then(setStyle);
  246. }
  247. )).observe(_de, { childList: true });
  248.  
  249. return style;
  250. }
  251.  
  252. // Fake objects of advertisement networks to break their workflow
  253. scriptLander(() => {
  254. let nt = new nullTools();
  255. // Popular adblock detector
  256. if (!('fuckAdBlock' in win)) {
  257. let FuckAdBlock = function(options) {
  258. let self = this;
  259. self._options = {
  260. checkOnLoad: false,
  261. resetOnEnd: false,
  262. checking: false
  263. };
  264. self.setOption = function(opt, val) {
  265. if (val)
  266. self._options[opt] = val;
  267. else
  268. Object.assign(self._options, opt);
  269. };
  270. if (options)
  271. self.setOption(options);
  272.  
  273. self._var = { event: {} };
  274. self.clearEvent = function() {
  275. self._var.event.detected = [];
  276. self._var.event.notDetected = [];
  277. };
  278. self.clearEvent();
  279.  
  280. self.on = function(detected, fun) {
  281. self._var.event[detected?'detected':'notDetected'].push(fun);
  282. return self;
  283. };
  284. self.onDetected = function(cb) {
  285. return self.on(true, cb);
  286. };
  287. self.onNotDetected = function(cb) {
  288. return self.on(false, cb);
  289. };
  290. self.emitEvent = function() {
  291. for (let fun of self._var.event.notDetected)
  292. fun();
  293. if (self._options.resetOnEnd)
  294. self.clearEvent();
  295. return self;
  296. };
  297. self._creatBait = () => null;
  298. self._destroyBait = () => null;
  299. self._checkBait = function() {
  300. setTimeout((() => self.emitEvent()), 1);
  301. };
  302. self.check = function() {
  303. self._checkBait();
  304. return true;
  305. };
  306.  
  307. let callback = function() {
  308. if (self._options.checkOnLoad)
  309. setTimeout(self.check, 1);
  310. };
  311. window.addEventListener('load', callback, false);
  312. };
  313. nt.define(win, 'FuckAdBlock', FuckAdBlock);
  314. nt.define(win, 'fuckAdBlock', new FuckAdBlock({
  315. checkOnLoad: true,
  316. resetOnEnd: true
  317. }));
  318. }
  319.  
  320. // CoinHive miner stub. Continuous 100% CPU load can easily kill some CPU with overheat.
  321. if (!('CoinHive' in win))
  322. if (location.hostname !== 'cnhv.co') {
  323. // CoinHive stub for cases when it doesn't affect site functionality
  324. let CoinHiveConstructor = function() {
  325. _console.warn('Fake CoinHive miner created.');
  326. this.setThrottle = nt.func(null);
  327. this.start = nt.func(null);
  328. this.on = nt.func(null);
  329. this.getHashesPerSecond = nt.func(Infinity);
  330. this.getTotalHashes = nt.func(Infinity);
  331. this.getAcceptedHashes = nt.func(Infinity);
  332. };
  333. let CoinHiveStub = nt.proxy({
  334. Anonymous: CoinHiveConstructor,
  335. User: CoinHiveConstructor,
  336. Token: CoinHiveConstructor,
  337. JobThread: nt.func(null),
  338. Res: nt.func(null),
  339. IF_EXCLUSIVE_TAB: false,
  340. CONFIG: nt.proxy({})
  341. });
  342. nt.define(win, 'CoinHive', CoinHiveStub);
  343. } else {
  344. // CoinHive wrapper to fool sites which expect it to actually work and return results
  345. let CoinHiveObject;
  346. Object.defineProperty(win, 'CoinHive', {
  347. set: function(obj) {
  348. if ('Token' in obj) {
  349. _console.log('[CoinHive] Token wrapper applied.');
  350. let _Token = obj.Token.bind(obj);
  351. obj.Token = function(siteKey, goal, params) {
  352. let _goal = goal;
  353. goal = goal > 256 ? 256 : goal;
  354. _console.log(`[CoinHive] Original goal: ${_goal}, new smaller goal ${goal}.`);
  355. _console.log(`With smaller goals server may return 'invalid_goal' error and stop working.`);
  356. let miner = _Token(siteKey, goal, params);
  357. miner.setThrottle(0.99);
  358. miner.setThrottle = () => null;
  359. let _start = miner.start.bind(miner);
  360. miner.start = function() {
  361. let res = _start(window.CoinHive.FORCE_EXCLUSIVE_TAB);
  362. return res;
  363. };
  364. let _getTotalHashes = miner.getTotalHashes;
  365. miner.getTotalHashes = function() {
  366. return Math.trunc(_getTotalHashes.call(this) / goal * _goal);
  367. };
  368. let __emit = miner._emit;
  369. miner._emit = function(state, props) {
  370. let _self = this;
  371. _console.log('[CoinHive] state:', state, props);
  372. if (state === 'job')
  373. setTimeout(() => {
  374. _self.stop();
  375. _self._emit('accepted', { hashes: goal });
  376. }, 1000);
  377. return __emit.apply(_self, arguments);
  378. };
  379. let _on = miner.on.bind(miner);
  380. miner.on = function(type, callback) {
  381. if (type === 'accepted') {
  382. _console.log('[CoinHive] "accepted" callback wrapper applied.');
  383. let _callback = callback;
  384. callback = function(params) {
  385. _console.log('[CoinHive] "accepted" callback is called, imitating original goal being reached.');
  386. params.hashes = _goal;
  387. return _callback.apply(this, arguments);
  388. };
  389. miner.stop();
  390. }
  391. return _on(type, callback);
  392. };
  393. return miner;
  394. };
  395. }
  396. CoinHiveObject = obj;
  397. },
  398. get: () => CoinHiveObject
  399. });
  400. }
  401.  
  402. // VideoJS player wrapper
  403. VideoJS: {
  404. let _videojs = win.videojs || void 0;
  405. Object.defineProperty(win, 'videojs', {
  406. get: () => _videojs,
  407. set: f => {
  408. if (f === _videojs)
  409. return true;
  410. _console.log('videojs =', f);
  411. _videojs = new Proxy(f, {
  412. apply: (tgt, ths, args) => {
  413. _console.log('videojs(', ...args, ')');
  414. let params = args[1];
  415. if (params) {
  416. if (params.hasAd)
  417. params.hasAd = false;
  418. if (params.autoplay)
  419. params.autoplay = false;
  420. if (params.plugins && params.plugins.vastClient)
  421. delete params.plugins.vastClient;
  422. }
  423. let res = tgt.apply(ths, args);
  424. if (res && res.seed)
  425. res.seed = () => null;
  426. _console.log('player = ', res);
  427. return res;
  428. }
  429. });
  430. }
  431. });
  432. }
  433.  
  434. // Set a little trap for BodyClick ads
  435. Object.defineProperty(win, '__BC_domain', {
  436. set: () => { throw 'BodyClick trap' }
  437. });
  438.  
  439. // Yandex API (ADBTools, Metrika)
  440. let hostname = location.hostname;
  441. if (// Thank you, Greasemonkey, now I have to check for this. -_-
  442. location.protocol === 'about:' ||
  443. // Google likes to define odd global variables like Ya
  444. hostname.startsWith('google.') || hostname.includes('.google.') ||
  445. // Also, Yandex uses their Ya object for a lot of things on their pages and
  446. // wrapping it may cause problems. It's better to skip it in some cases.
  447. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  448. /^\/((yand)?search|images)/i.test(location.pathname) && !hostname.startsWith('news.')) ||
  449. // Also skip on these following sites since they use
  450. // code minification which generated global Ya variable.
  451. hostname.endsWith('chatango.com') || hostname.endsWith('github.io') ||
  452. hostname.endsWith('grimtools.com') || hostname.endsWith('poeplanner.com'))
  453. return;
  454.  
  455. let YaProps = new Set();
  456. function setObfuscatedProperty(Ya, rootProp, obj, name) {
  457. if (YaProps.has(rootProp))
  458. return;
  459. _console.warn(`Ya.${rootProp} = Ya.${name}`);
  460. nt.define(Ya, rootProp, Ya[name]);
  461. YaProps.add(rootProp);
  462. for (let prop in obj)
  463. delete obj[prop];
  464. for (let prop in Ya[name])
  465. obj[prop] = Ya[name][prop];
  466. }
  467. function onObfuscatedProperty (Ya, rootProp, obj) {
  468. if ('AdvManager' in obj || 'isAllowedRepeatAds' in obj) {
  469. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  470. return Ya.Context;
  471. }
  472. if ('create' in obj && 'createAdaptive' in obj && 'createScroll' in obj) {
  473. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  474. return Ya.adfoxCode;
  475. }
  476. return new Proxy(obj, {
  477. set: (tgt, prop, val) => {
  478. if (prop === 'AdvManager' || prop === 'isAllowedRepeatAds') {
  479. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  480. return true;
  481. }
  482. if (prop === 'create' && 'createAdaptive' in obj && 'createScroll' in obj ||
  483. prop === 'createScroll' && 'create' in obj && 'createAdaptive' in obj ||
  484. prop === 'createAdaptive' && 'create' in obj && 'createScroll' in obj) {
  485. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  486. return true;
  487. }
  488. tgt[prop] = val;
  489. return true;
  490. },
  491. get: (tgt, prop) => {
  492. if (prop === 'AdvManager' && !(prop in tgt)) {
  493. _console.warn(`Injected missing ${prop} in Ya.${rootProp}.`);
  494. tgt[prop] = Ya.Context[prop];
  495. }
  496. return tgt[prop];
  497. }
  498. });
  499. }
  500. let Rum = {};
  501. [
  502. '__timeMarks', '_timeMarks', '__deltaMarks', '_deltaMarks',
  503. '__defRes', '_defRes', '__defTimes', '_defTimes', '_vars',
  504. 'commonVars'
  505. ].forEach(name => void(Rum[name] = []));
  506. [
  507. 'getSettings', 'getVarsList'
  508. ].forEach(name => void(Rum[name] = nt.func([], `Ya.Rum.${name}`)));
  509. [
  510. ['ajaxStart', 0], ['ajaxComplete', 0],
  511. ['enabled', true], ['_tti', null],
  512. ['vsChanged', false], ['vsStart', 'visible']
  513. ].forEach(([prop, val]) => void(Rum[prop] = val));
  514. Rum = nt.proxy(Rum, 'Ya.Rum', null);
  515. let Ya = new Proxy({}, {
  516. set: function(tgt, prop, val) {
  517. if (val === tgt[prop])
  518. return true;
  519. if (prop === 'Rum') {
  520. nt.define(tgt, prop, Rum);
  521. YaProps.add(prop);
  522. Object.assign(val, Rum);
  523. }
  524. if (YaProps.has(prop)) {
  525. _console.log(`Ya.${prop} \u2260`, val);
  526. return true;
  527. }
  528. if (val instanceof Object && prop !== '__inline_params__')
  529. val = onObfuscatedProperty(Ya, prop, val);
  530. tgt[prop] = val;
  531. _console.log(`Ya.${prop} =`, val);
  532. return true;
  533. },
  534. get: (tgt, prop) => tgt[prop]
  535. });
  536. let callWithParams = function(f) {
  537. f.call(this, Ya.__inline_params__ || {});
  538. Ya.__inline_params__ = null;
  539. };
  540. nt.define(Ya, 'callWithParams', callWithParams);
  541. nt.define(Ya, 'PerfCounters', nt.proxy({
  542. __cacheEvents: []
  543. }, 'Ya.PerfCounters', null));
  544. nt.define(Ya, '__isSent', true);
  545. nt.define(Ya, 'confirmUrl', '');
  546. nt.define(Ya, 'Direct', nt.proxy({}, 'Ya.Direct', null));
  547. nt.define(Ya, 'mediaCode', nt.proxy({
  548. create: function() {
  549. if (inIFrame) {
  550. _console.log('Removed body of ad-frame.');
  551. _document.documentElement.removeChild(_document.body);
  552. }
  553. }
  554. }, 'Ya.mediaCode', null));
  555. let extra = nt.proxy({
  556. extra: nt.proxy({ match: 0, confirm: '', src: '' }),
  557. id: 0, percent: 100, threshold: 1
  558. });
  559. nt.define(Ya, '_exp', nt.proxy({
  560. id: 0, coin: 0,
  561. choose: nt.func(extra),
  562. get: (prop) => extra.hasOwnProperty(prop) ? extra[prop] : null,
  563. getId: nt.func(0),
  564. defaultVersion: extra,
  565. getExtra: nt.func(extra.extra),
  566. getDefaultExtra: nt.func(extra.extra),
  567. versions: [extra]
  568. }));
  569. nt.define(Ya, 'c', nt.func(null));
  570. nt.define(Ya, 'ADBTools', function(){
  571. this.getCurrentState = nt.func(true);
  572. return nt.proxy(this, 'Ya.ADBTools', null);
  573. });
  574. nt.define(Ya, 'AdDetector', nt.proxy({}, 'Ya.AdDetector', null));
  575. let adfoxCode = {
  576. forcedDirectLoadingExp: nt.proxy({ isLoadingTurnedOn: false, isExp: false }),
  577. isLoadingTurnedOn: false,
  578. xhrExperiment: nt.proxy({ isXhr: true, isControl: true }),
  579. pr: 0, _: []
  580. };
  581. [
  582. 'clearSession', 'create', 'createAdaptive', 'createScroll',
  583. 'destroy', 'moduleLoad', 'reload', 'setModule'
  584. ].forEach(name => void(adfoxCode[name] = nt.func(null, `Ya.adfoxCode.${name}`)));
  585. nt.define(Ya, 'adfoxCode', nt.proxy(adfoxCode, 'Ya.adfoxCode', null));
  586. let managerForAdfox = {
  587. loaderVersion: 1,
  588. isCurrrencyExp: true,
  589. isReady: nt.func(true, 'Ya.headerBidding.managerForAdfox.isReady'),
  590. getRequestTimeout: nt.func(300 + Math.floor(Math.random()*100), 'Ya.headerBidding.managerForAdfox.getRequestTimeout')
  591. };
  592. let headerBidding = nt.proxy({
  593. setSettings: opts => {
  594. if (!(opts && opts.adUnits))
  595. return null;
  596. let ids = [];
  597. for (let unit of opts.adUnits)
  598. ids.push(unit.code);
  599. createStyle(`#${ids.join(', #')} { display: none !important }`);
  600. },
  601. managerForAdfox: nt.proxy(managerForAdfox, 'Ya.headerBidding.managerForAdfox', null)
  602. });
  603. nt.define(Ya, 'headerBidding', headerBidding);
  604.  
  605. let AdvManager = function() {
  606. this.render = function(o) {
  607. if (!o.renderTo)
  608. return;
  609. let placeholder = _document.getElementById(o.renderTo);
  610. if (!placeholder)
  611. return _console.warn('Ya.AdvManager.render call w/o placeholder', o);
  612. let parent = placeholder.parentNode;
  613. placeholder.style = 'display:none!important';
  614. parent.style = (parent.getAttribute('style')||'') + 'height:auto!important';
  615. // fix for Yandex TV pages
  616. if (location.hostname.startsWith('tv.yandex.')) {
  617. let sibling = placeholder.previousSibling;
  618. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  619. sibling.style.display = 'none';
  620. }
  621. };
  622. this.constructor = Object;
  623. return nt.proxy(this, 'Ya.AdvManager', null);
  624. };
  625. nt.define(Ya, 'Context', nt.proxy({
  626. __longExperiment: null,
  627. _callbacks: nt.proxy([]),
  628. _asyncModeOn: true,
  629. _init: nt.func(null),
  630. isAllowedRepeatAds: nt.func(null),
  631. isNewLoader: nt.func(false),
  632. AdvManager: new AdvManager(),
  633. AdvManagerStatic: nt.func({})
  634. }));
  635. let Metrika = function Metrika(x) {
  636. this._ecommerce = '';
  637. if (x && 'id' in x)
  638. this.id = x.id;
  639. else
  640. this.id = 0;
  641. return nt.proxy(this, 'Ya.Metrika', null);
  642. };
  643. Metrika.counters = () => Ya._metrika.counters;
  644. nt.define(Ya, 'Metrika', Metrika);
  645. nt.define(Ya, 'Metrika2', Metrika);
  646. let counter = new Ya.Metrika();
  647. nt.define(Ya, '_metrika', nt.proxy({
  648. counter: counter,
  649. counters: [counter],
  650. hitParam: {},
  651. counterNum: 0,
  652. hitId: 0,
  653. v: 1,
  654. i: 0,
  655. _globalMetrikaHitId: 0,
  656. getCounters: null,
  657. dataLayer: null,
  658. f1: null
  659. }));
  660. nt.define(Ya, '_globalMetrikaHitId', 0);
  661. counter = {};
  662. [
  663. 'stringifyParams','_getVars',
  664. 'getUid','getUrl','getHash'
  665. ].forEach(name => void(counter[name] = nt.func('', `Ya.counter.${name}`)));
  666. nt.define(Ya, 'counter', nt.proxy(counter, 'Ya.counter', null));
  667. nt.define(Ya, 'jserrors', []);
  668. nt.define(Ya, 'onerror', nt.func(null, 'Ya.onerror'));
  669. let error_on_access = false;
  670. if ('Ya' in win)
  671. try {
  672. _console.log('Found existing Ya object:', win.Ya);
  673. for (let prop in win.Ya)
  674. Ya[prop] = win.Ya[prop];
  675. } catch(ignore) {
  676. error_on_access = true;
  677. }
  678. if (!error_on_access) {
  679. for (let prop in Ya)
  680. if (prop !== '__inline_params__')
  681. YaProps.add(prop);
  682. nt.define(win, 'Ya', Ya);
  683. } else
  684. _console.log('Looks like window.Ya blocked with error-on-access scriptlet.');
  685. // Yandex.Metrika callbacks
  686. let yandex_metrika_callbacks = [];
  687. _document.addEventListener(
  688. 'DOMContentLoaded', () => {
  689. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  690. yandex_metrika_callbacks.length = 0;
  691. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  692. }, false
  693. );
  694. nt.define(win, 'yandex_metrika_callbacks', yandex_metrika_callbacks);
  695. }, nullTools, createStyle);
  696.  
  697. if (!isFirefox) {
  698. // scripts for non-Firefox browsers
  699. // https://greasyfork.org/scripts/14720-it-s-not-important
  700. unimptt: {
  701. // BigInt were implemented in Chrome 67 which also support
  702. // proper user styles and doesn't need this fix anymore.
  703. if ((isChrome || isOpera) && 'BigInt' in win)
  704. break unimptt;
  705.  
  706. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  707. ret_b = (a,b) => b,
  708. _toLowerCase = String.prototype.toLowerCase,
  709. protectedNodes = new WeakSet(),
  710. log = false;
  711.  
  712. let logger = function() {
  713. if (log)
  714. _console.log('Some page elements became a bit less important.');
  715. log = false;
  716. };
  717.  
  718. let unimportanter = function(node) {
  719. let style = (node.nodeType === _Node.ELEMENT_NODE) ?
  720. _getAttribute(node, 'style') : null;
  721.  
  722. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  723. (node.src && node.src.startsWith('chrome-extension:'))) // Web of Trust IFRAME and similar
  724. return false; // get out if we have nothing to do here
  725.  
  726. protectedNodes.add(node);
  727. _setAttribute(node, 'style', style.replace(imptt, ret_b));
  728. log = true;
  729. };
  730.  
  731. (new MutationObserver(
  732. function(mutations) {
  733. setTimeout(
  734. function(ms) {
  735. let m, node;
  736. for (m of ms) for (node of m.addedNodes)
  737. unimportanter(node);
  738. logger();
  739. }, 0, mutations
  740. );
  741. }
  742. )).observe(_document, {
  743. childList : true,
  744. subtree : true
  745. });
  746.  
  747. _Element.setAttribute = function setAttribute(name, value) {
  748. '[native code]';
  749. let replaced = value;
  750. if (name && _toLowerCase.call(name) === 'style' && protectedNodes.has(this))
  751. replaced = value.replace(imptt, ret_b);
  752. log = (replaced !== value);
  753. logger();
  754. return _setAttribute(this, ...arguments);
  755. };
  756.  
  757. win.addEventListener (
  758. 'load', () => {
  759. for (let imp of _document.querySelectorAll('[style*="!"]'))
  760. unimportanter(imp);
  761. logger();
  762. }, false
  763. );
  764. }
  765.  
  766. // Naive ABP Style protector
  767. if ('ShadowRoot' in win) {
  768. let _querySelector = _Document.querySelector.bind(_document);
  769. let _removeChild = Function.prototype.call.bind(_Node.removeChild);
  770. let _appendChild = Function.prototype.call.bind(_Node.appendChild);
  771. let createShadow = () => _createElement('shadow');
  772. // Prevent adding fake content entry point
  773. _Node.appendChild = function appendChild(child) {
  774. if (this instanceof ShadowRoot &&
  775. child instanceof HTMLContentElement)
  776. return _appendChild(this, createShadow());
  777. return _appendChild(this, ...arguments);
  778. };
  779. {
  780. let _shadowSelector = Function.prototype.call.bind(ShadowRoot.prototype.querySelector);
  781. let _innerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
  782. let _parentNode = Object.getOwnPropertyDescriptor(_Node, 'parentNode');
  783. if (_innerHTML && _parentNode) {
  784. let _set = Function.prototype.call.bind(_innerHTML.set);
  785. let _getParent = Function.prototype.call.bind(_parentNode.get);
  786. _innerHTML.configurable = false;
  787. _innerHTML.set = function() {
  788. _set(this, ...arguments);
  789. let content = _shadowSelector(this, 'content');
  790. if (content) {
  791. let parent = _getParent(content);
  792. _removeChild(parent, content);
  793. _appendChild(parent, createShadow());
  794. }
  795. };
  796. }
  797. Object.defineProperty(ShadowRoot.prototype, 'innerHTML', _innerHTML);
  798. }
  799. // Locate and apply extra protection to a style on top of what ABP does
  800. let style;
  801. (new Promise(
  802. function(resolve, reject) {
  803. let getStyle = () => _querySelector('::shadow style');
  804. style = getStyle();
  805. if (style)
  806. return resolve(style);
  807. let intv = setInterval(
  808. function() {
  809. style = getStyle();
  810. if (!style)
  811. return;
  812. intv = clearInterval(intv);
  813. return resolve(style);
  814. }, 0
  815. );
  816. _document.addEventListener(
  817. 'DOMContentLoaded', () => {
  818. if (intv)
  819. clearInterval(intv);
  820. style = getStyle();
  821. return style ? resolve(style) : reject();
  822. }, false
  823. );
  824. }
  825. )).then(
  826. function(style) {
  827. let emptyArr = [],
  828. nullStr = {
  829. get: () => '',
  830. set: () => undefined
  831. };
  832. let shadow = style.parentNode;
  833. Object.defineProperties(shadow, {
  834. childElementCount: { value: 0 },
  835. styleSheets: { value: emptyArr },
  836. firstChild: { value: null },
  837. firstElementChild: { value: null },
  838. lastChild: { value: null },
  839. lastElementChild: { value: null },
  840. childNodes: { value: emptyArr },
  841. children: { value: emptyArr },
  842. innerHTML: { value: nullStr },
  843. });
  844. Object.defineProperties(style, {
  845. innerHTML: { value: nullStr },
  846. textContent: { value: nullStr },
  847. ownerDocument: { value: null },
  848. parentNode: {value: null },
  849. previousElementSibling: { value: null },
  850. previousSibling: { value: null },
  851. disabled: { get: () => true, set: () => null }
  852. });
  853. Object.defineProperties(style.sheet, {
  854. deleteRule: { value: () => null },
  855. disabled: { get: () => true, set: () => null },
  856. cssRules: { value: emptyArr },
  857. rules: { value: emptyArr }
  858. });
  859. }
  860. ).catch(()=>null);
  861. _Node.removeChild = function removeChild(child) {
  862. if (child === style)
  863. return;
  864. return _removeChild(this, ...arguments);
  865. };
  866. }
  867. }
  868.  
  869. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^/]+\/(yand)?search[/?])/i.test(win.location.href) ||
  870. /^https?:\/\/tv\.yandex\./i.test(win.location.href)) {
  871. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  872. let yadWord = /Яндекс.Директ/i,
  873. adWords = /Реклама|Ad/i;
  874. let _querySelector = _document.querySelector.bind(_document),
  875. _querySelectorAll = _document.querySelectorAll.bind(_document),
  876. _getAttribute = Function.prototype.call.bind(_Element.getAttribute),
  877. _setAttribute = Function.prototype.call.bind(_Element.setAttribute);
  878. // Function to attach an observer to monitor dynamic changes on the page
  879. let pageUpdateObserver = (func, obj, params) => {
  880. if (obj)
  881. (new MutationObserver(func))
  882. .observe(obj, (params || { childList:true, subtree:true }));
  883. };
  884. // Short name for parentNode.removeChild and setAttribute style to display:none
  885. let remove = (node) => {
  886. if (!node || !node.parentNode)
  887. return false;
  888. _console.log('Removed node.');
  889. node.parentNode.removeChild(node);
  890. };
  891. let hide = (node) => {
  892. if (!node)
  893. return false;
  894. _console.log('Hid node.');
  895. _setAttribute(node, 'style', 'display:none!important');
  896. };
  897. // Yandex search ads in Google Chrome
  898. if ('attachShadow' in _Element) {
  899. let _attachShadow = _Element.attachShadow;
  900. _Element.attachShadow = function() {
  901. let node = this,
  902. root = _attachShadow.apply(node, arguments);
  903. pageUpdateObserver(
  904. (ms) => {
  905. for (let m of ms) if (m.addedNodes.length)
  906. if (adWords.test(root.textContent))
  907. remove(node.closest('.serp-item'));
  908. }, root
  909. );
  910. return root;
  911. };
  912. }
  913. // Yandex Mail ads
  914. if (location.hostname.startsWith('mail.')) {
  915. let nt = new nullTools();
  916. let wrap = vl => {
  917. if (!vl)
  918. return vl;
  919. _console.log('Daria =', vl);
  920. nt.define(vl, 'AdBlock', nt.proxy({
  921. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  922. enabled: false
  923. }));
  924. nt.define(vl, 'AdvPresenter', nt.proxy({
  925. _config: nt.proxy({
  926. banner: false,
  927. done: false,
  928. line: true
  929. })
  930. }));
  931. if (vl.Config) {
  932. delete vl.Config.adBlockDetector;
  933. delete vl.Config['adv-url'];
  934. delete vl.Config.cryprox;
  935. if (vl.Config.features) {
  936. delete vl.Config.features.web_adloader_with_cookie_cache;
  937. delete vl.Config.features.web_ads;
  938. delete vl.Config.features.web_ads_mute;
  939. }
  940. vl.Config.mayHaveAdv = false;
  941. }
  942. return vl;
  943. };
  944. let _Daria = wrap(win.Daria);
  945. if (_Daria)
  946. _console.log('Wrapped already existing object "Daria".');
  947. Object.defineProperty(win, 'Daria', {
  948. get: () => _Daria,
  949. set: vl => {
  950. if (vl === _Daria)
  951. return;
  952. _Daria = wrap(vl);
  953. }
  954. });
  955. }
  956. // prevent/defuse adblock detector
  957. setInterval(() => {
  958. localStorage.ic = '';
  959. localStorage._mt__data = '';
  960. }, 100);
  961. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  962. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  963. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  964. if (_cookie) {
  965. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  966. _cookie.set = function(value) {
  967. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  968. // remove value, set expired
  969. if (!value.startsWith('yp=')) {
  970. value = value.replace(/^([^=]+=)[^;]+/,'$1').replace(/(expires=)[\w\s\d,]+/,'$1Thu, 01 Jan 1970 00');
  971. _console.log('expire cookie', value.match(/^[^=]+/)[0]);
  972. } else {
  973. let parts = value.split(';');
  974. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  975. if (values.length)
  976. values[0] = values[0].replace(/^yp=/, '');
  977. let res = `yp=${values.join('#')}`;
  978. _console.log(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  979. parts[0] = res;
  980. value = parts.join(';');
  981. }
  982. return _set_cookie(this, value);
  983. };
  984. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  985. }
  986. // other ads
  987. _document.addEventListener(
  988. 'DOMContentLoaded', () => {
  989.  
  990. {
  991. // Generic ads removal and fixes
  992. let node = _querySelector('.serp-header');
  993. if (node)
  994. node.style.marginTop = '0';
  995. for (node of _querySelectorAll(
  996. '.serp-adv__head + .serp-item,'+
  997. '#adbanner,'+
  998. '.serp-adv,'+
  999. '.b-spec-adv,'+
  1000. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  1001. )) remove(node);
  1002. }
  1003. // Search ads
  1004. function removeSearchAds() {
  1005. for (let node of _querySelectorAll('.serp-item'))
  1006. if (_getAttribute(node, 'role') === 'complementary' ||
  1007. adWords.test((node.querySelector('.label')||{}).textContent))
  1008. hide(node);
  1009. }
  1010. // News ads
  1011. function removeNewsAds() {
  1012. let node, block, items, mask, classes,
  1013. masks = [
  1014. { class: '.ads__wrapper', regex: /[^,]*?,[^,]*?\.ads__wrapper/ },
  1015. { class: '.ads__pool', regex: /[^,]*?,[^,]*?\.ads__pool/ }
  1016. ];
  1017. for (node of _querySelectorAll('style[nonce]')) {
  1018. classes = node.innerText.replace(/\{[^}]+\}+/ig, '|').split('|');
  1019. for (block of classes) for (mask of masks)
  1020. if (block.includes(mask.class)) {
  1021. block = block.match(mask.regex)[0];
  1022. items = _querySelectorAll(block);
  1023. for (item of items)
  1024. remove(items[0]);
  1025. }
  1026. }
  1027. }
  1028. // Music ads
  1029. function removeMusicAds() {
  1030. for (let node of _querySelectorAll('.ads-block'))
  1031. remove(node);
  1032. }
  1033. // News fixes
  1034. function removePageAdsClass() {
  1035. if (_document.body.classList.contains("b-page_ads_yes")) {
  1036. _document.body.classList.remove("b-page_ads_yes");
  1037. _console.log('Page ads class removed.');
  1038. }
  1039. }
  1040. // TV fixes
  1041. function removeTVAds() {
  1042. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  1043. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  1044. if (node.offsetWidth) {
  1045. let pad = _document.createElement('div');
  1046. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  1047. node.parentNode.appendChild(pad);
  1048. }
  1049. remove(node);
  1050. }
  1051. }
  1052.  
  1053. if (location.hostname.startsWith('music.')) {
  1054. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1055. removeMusicAds();
  1056. } else if (location.hostname.startsWith('news.')) {
  1057. pageUpdateObserver(removeNewsAds, _document.body);
  1058. pageUpdateObserver(removePageAdsClass, _document.body, { attributes:true, attributesFilter:['class'] });
  1059. removeNewsAds();
  1060. removePageAdsClass();
  1061. } else if (location.hostname.startsWith('tv.')) {
  1062. pageUpdateObserver(removeTVAds, _document.body);
  1063. removeTVAds();
  1064. } else if (!location.hostname.startsWith('mail.')) {
  1065. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  1066. removeSearchAds();
  1067. }
  1068. }
  1069. );
  1070. }
  1071.  
  1072. // Generic Yandex Scripts
  1073. if (/^https?:\/\/([^.]+\.)*yandex\.[^/]+/i.test(win.location.href)) {
  1074. // remove banner on the start page
  1075. scriptLander(() => {
  1076. let nt = new nullTools({log: false, trace: true});
  1077. let AwapsJsonAPI_Json = function(...args) {
  1078. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  1079. };
  1080. [
  1081. 'setID', 'addImageContent',
  1082. 'sendCounts', 'expand', 'refreshAd'
  1083. ].forEach(name => void(AwapsJsonAPI_Json.prototype[name] = nt.func(null, `AwapsJsonAPI.Json.${name}`)));
  1084. AwapsJsonAPI_Json.prototype.checkBannerVisibility = nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility');
  1085. AwapsJsonAPI_Json.prototype.addIframeContent = nt.proxy(function(...args) {
  1086. try {
  1087. let frame = args[1][0].parentNode;
  1088. frame.parentNode.removeChild(frame);
  1089. _console.log(`Removed banner placeholder.`);
  1090. } catch(ignore) {
  1091. _console.log(`Can't locate frame object to remove.`);
  1092. }
  1093. });
  1094. AwapsJsonAPI_Json.prototype.getHTML = nt.func('', 'AwapsJsonAPI.Json.getHTML');
  1095. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype);
  1096. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  1097. if ('AwapsJsonAPI' in win) {
  1098. _console.log('Oops! AwapsJsonAPI already defined.');
  1099. let f = win.AwapsJsonAPI.Json;
  1100. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1101. if (f && f.prototype)
  1102. f.prototype = AwapsJsonAPI_Json.prototype;
  1103. } else
  1104. nt.define(win, 'AwapsJsonAPI', nt.proxy({
  1105. Json: AwapsJsonAPI_Json
  1106. }));
  1107.  
  1108. let parseExport = x => {
  1109. if (!x)
  1110. return x;
  1111. // remove banner placeholder
  1112. if (x.banner && x.banner.cls) {
  1113. let _parent = `.${x.banner.cls.banner__parent}`;
  1114. _document.addEventListener('DOMContentLoaded', () => {
  1115. for (let banner of _document.querySelectorAll(_parent)) {
  1116. _setAttribute(banner, 'style', 'display:none!important');
  1117. _console.log('Hid banner placeholder.');
  1118. }
  1119. }, false);
  1120. }
  1121.  
  1122. // remove banner data and some other stuff
  1123. delete x.banner;
  1124. delete x.consistency;
  1125. delete x['i-bannerid'];
  1126. delete x['i-counter'];
  1127. delete x['promo-curtain'];
  1128.  
  1129. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  1130. if (x['ga-counter'] && x['ga-counter'].data) {
  1131. x['ga-counter'].data.id = 0;
  1132. delete x['ga-counter'].data.ether;
  1133. delete x['ga-counter'].data.iframeSrc;
  1134. delete x['ga-counter'].data.iframeSrcEx;
  1135. }
  1136.  
  1137. return x;
  1138. };
  1139. // Yandex banner on main page and some other things
  1140. let _home = win.home,
  1141. _home_set = !!_home;
  1142. Object.defineProperty(win, 'home', {
  1143. get: () => _home,
  1144. set: vl => {
  1145. if (!_home_set && vl === _home)
  1146. return;
  1147. _home_set = false;
  1148. _console.log('home =', vl);
  1149. let _home_export = parseExport(vl.export);
  1150. Object.defineProperty(vl, 'export', {
  1151. get: () => _home_export,
  1152. set: vl => {
  1153. _home_export = parseExport(vl);
  1154. }
  1155. });
  1156. _home = vl;
  1157. }
  1158. });
  1159. // adblock circumvention on some Yandex domains (weather in particular)
  1160. nt.define(win, 'Raven', nt.proxy({
  1161. captureMessage: nt.func(null, 'Raven.captureMessage'),
  1162. config: nt.func({
  1163. install: nt.func(null, 'Raven.config().install')
  1164. }, 'Raven.config')
  1165. }));
  1166. }, nullTools, 'let _setAttribute = Function.prototype.call.bind(_Element.setAttribute)');
  1167.  
  1168. if ('attachShadow' in _Element) {
  1169. let fakeRoot = () => ({
  1170. firstChild: null,
  1171. appendChild: () => null,
  1172. querySelector: () => null,
  1173. querySelectorAll: () => null
  1174. });
  1175. _Element.createShadowRoot = fakeRoot;
  1176. let shadows = new WeakMap();
  1177. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  1178. _attachShadow.value = function() {
  1179. return shadows.set(this, fakeRoot()).get(this);
  1180. };
  1181. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  1182. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  1183. _shadowRoot.set = () => null;
  1184. _shadowRoot.get = function() {
  1185. return shadows.has(this) ? shadows.get(this) : void 0;
  1186. };
  1187. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  1188. }
  1189.  
  1190. // Disable banner styleSheet (on main page)
  1191. document.addEventListener('DOMContentLoaded', () => {
  1192. for (let sheet of document.styleSheets)
  1193. try {
  1194. for (let rule of sheet.cssRules)
  1195. if (rule.cssText.includes(' 728px 90px')) {
  1196. rule.parentStyleSheet.disabled = true;
  1197. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  1198. }
  1199. } catch(ignore) {}
  1200. }, false);
  1201.  
  1202. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1203. let selectors = (
  1204. 'A[onmousedown*="/jsredir"],'+
  1205. 'A[data-vdir-href],'+
  1206. 'A[data-counter]'
  1207. );
  1208. let removeTrackingAttributes = function(link) {
  1209. link.removeAttribute('onmousedown');
  1210. if (link.hasAttribute('data-vdir-href')) {
  1211. link.removeAttribute('data-vdir-href');
  1212. link.removeAttribute('data-orig-href');
  1213. }
  1214. if (link.hasAttribute('data-counter')) {
  1215. link.removeAttribute('data-counter');
  1216. link.removeAttribute('data-bem');
  1217. }
  1218. };
  1219. let removeTracking = function(scope) {
  1220. if (scope instanceof Element)
  1221. for (let link of scope.querySelectorAll(selectors))
  1222. removeTrackingAttributes(link);
  1223. };
  1224. _document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1225. (new MutationObserver(
  1226. function(ms) {
  1227. let m, node;
  1228. for (m of ms) for (node of m.addedNodes)
  1229. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  1230. removeTrackingAttributes(node);
  1231. else
  1232. removeTracking(node);
  1233. }
  1234. )).observe(_de, { childList: true, subtree: true });
  1235. }
  1236.  
  1237. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1238. _document.addEventListener(
  1239. 'DOMContentLoaded', function() {
  1240. let log = name => _console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1241. function removeVast (data) {
  1242. if (data && (data.vast || data.reserve_vast || data.vast_button)) {
  1243. _console.log('Removed:\ndata.vast', data.vast, '\ndata.reserve_vast', data.reserve_vast, '\ndata.vast_button', data.vast_button);
  1244. delete data.vast;
  1245. delete data.reserve_vast;
  1246. delete data.vast_button;
  1247. if (data.chain) {
  1248. let need = [],
  1249. drop = [],
  1250. links = data.chain.split('.');
  1251. for (let link of links)
  1252. if (!/^vast_|_vast_|_vast$/.test(link))
  1253. need.push(link);
  1254. else
  1255. drop.push(link);
  1256. _console.log('Dropped from the chain:', ...drop);
  1257. data.chain = need.join('.');
  1258. }
  1259. }
  1260. return data;
  1261. }
  1262. if (win.video_balancer !== void 0 && win.event_callback !== void 0) {
  1263. log('Moonwalk');
  1264. if (video_balancer.adv_loader)
  1265. removeVast(video_balancer.adv_loader.options);
  1266. if ('_mw_adb' in win)
  1267. Object.defineProperty(win, '_mw_adb', {
  1268. get: () => false,
  1269. set: () => true
  1270. });
  1271. /*} else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined) {
  1272. log('HDGo');
  1273. _document.body.onclick = null;
  1274. let tmp = _document.querySelector('#swtf');
  1275. if (tmp)
  1276. tmp.style.display = 'none';
  1277. if (win.banner_second !== void 0)
  1278. win.banner_second = 0;
  1279. if (win.$banner_ads !== void 0)
  1280. win.$banner_ads = false;
  1281. if (win.$new_ads !== void 0)
  1282. win.$new_ads = false;
  1283. if (win.createCookie !== void 0)
  1284. win.createCookie('popup', 'true', '999');
  1285. if (win.canRunAds !== void 0 && win.canRunAds !== true)
  1286. win.canRunAds = true;*/
  1287. } else if (win.startKodikPlayer !== void 0) {
  1288. log('Kodik');
  1289. // skip attempt to block access to HD resolutions
  1290. let chainCall = new Proxy({}, { get: () => () => chainCall });
  1291. if ($ && $.prototype && $.prototype.addClass) {
  1292. let $addClass = $.prototype.addClass;
  1293. $.prototype.addClass = function (className) {
  1294. if (className === 'blocked')
  1295. return chainCall;
  1296. return $addClass.apply(this, arguments);
  1297. };
  1298. }
  1299. // remove ad links from the metadata
  1300. let _ajax = win.$.ajax;
  1301. win.$.ajax = (params, ...args) => {
  1302. if (params.success) {
  1303. let _s = params.success;
  1304. params.success = (data, ...args) => _s(removeVast(data), ...args);
  1305. }
  1306. return _ajax(params, ...args);
  1307. }
  1308. } else if (win.getnextepisode && win.uppodEvent) {
  1309. log('Share-Serials.net');
  1310. scriptLander(
  1311. function() {
  1312. let _setInterval = win.setInterval,
  1313. _setTimeout = win.setTimeout,
  1314. _toString = Function.prototype.call.bind(Function.prototype.toString);
  1315. win.setInterval = function(func) {
  1316. if (func instanceof Function && _toString(func).includes('_delay')) {
  1317. let intv = _setInterval.call(
  1318. this, function() {
  1319. _setTimeout.call(
  1320. this, function(intv) {
  1321. clearInterval(intv);
  1322. let timer = _document.querySelector('#timer');
  1323. if (timer)
  1324. timer.click();
  1325. }, 100, intv);
  1326. func.call(this);
  1327. }, 5
  1328. );
  1329.  
  1330. return intv;
  1331. }
  1332. return _setInterval.apply(this, arguments);
  1333. };
  1334. win.setTimeout = function(func) {
  1335. if (func instanceof Function && _toString(func).includes('adv_showed'))
  1336. return _setTimeout.call(this, func, 0);
  1337. return _setTimeout.apply(this, arguments);
  1338. };
  1339. }
  1340. );
  1341. } else if ('ADC' in win) {
  1342. log('vjs-creatives plugin in');
  1343. let replacer = (obj) => {
  1344. for (let name in obj)
  1345. if (obj[name] instanceof Function)
  1346. obj[name] = () => null;
  1347. };
  1348. replacer(win.ADC);
  1349. replacer(win.currentAdSlot);
  1350. }
  1351. UberVK: {
  1352. if (!inIFrame)
  1353. break UberVK;
  1354. let oddNames = 'HD' in win &&
  1355. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1356. if (!oddNames)
  1357. break UberVK;
  1358. log('UberVK');
  1359. XMLHttpRequest.prototype.open = () => {
  1360. throw 404;
  1361. };
  1362. }
  1363. }, false
  1364. );
  1365.  
  1366. // Applies wrapper function on the current page and all newly created same-origin iframes
  1367. // This is used to prevent trick which allows to get fresh page API through newly created same-origin iframes
  1368. function deepWrapAPI(wrapper) {
  1369. let wrapped = new WeakSet(),
  1370. _get_contentWindow = () => null,
  1371. log = (...args) => false && _console.log(...args);
  1372. let wrapAPI = root => {
  1373. if (!root || wrapped.has(root))
  1374. return;
  1375. wrapped.add(root);
  1376. try {
  1377. wrapper(root instanceof HTMLIFrameElement ? _get_contentWindow(root) : root);
  1378. log('Wrapped API in', (root === win) ? "main window." : root);
  1379. } catch(e) {
  1380. log('Failed to wrap API in', (root === win) ? "main window." : root, '\n', e);
  1381. }
  1382. };
  1383.  
  1384. // wrap API on contentWindow access
  1385. let _apply = Function.prototype.apply;
  1386. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  1387. _get_contentWindow = _apply.bind(_contentWindow.get);
  1388. _contentWindow.get = function() {
  1389. wrapAPI(this);
  1390. return _get_contentWindow(this);;
  1391. };
  1392. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  1393.  
  1394. // wrap API on contentDocument access
  1395. let _contentDocument = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentDocument');
  1396. let _get_contentDocument = _apply.bind(_contentDocument.get);
  1397. _contentDocument.get = function() {
  1398. wrapAPI(this);
  1399. return _get_contentDocument(this);
  1400. };
  1401. Object.defineProperty(HTMLIFrameElement.prototype, 'contentDocument', _contentDocument);
  1402.  
  1403. // manual children objects traverser to avoid issues
  1404. // with calling querySelectorAll on wrong types of objects
  1405. let _nodeType = _apply.bind(Object.getOwnPropertyDescriptor(_Node, 'nodeType').get);
  1406. let _childNodes = _apply.bind(Object.getOwnPropertyDescriptor(_Node, 'childNodes').get);
  1407. let _ELEMENT_NODE = _Node.ELEMENT_NODE;
  1408. let _DOCUMENT_FRAGMENT_NODE = _Node.DOCUMENT_FRAGMENT_NODE
  1409. let wrapFrames = root => {
  1410. if (_nodeType(root) !== _ELEMENT_NODE && _nodeType(root) !== _DOCUMENT_FRAGMENT_NODE)
  1411. return; // only process nodes which may contain an IFRAME or be one
  1412. if (root instanceof HTMLIFrameElement) {
  1413. wrapAPI(root);
  1414. return;
  1415. }
  1416. for (let child of _childNodes(root))
  1417. wrapFrames(child);
  1418. };
  1419.  
  1420. // wrap API in a newly appended iframe objects
  1421. let _appendChild = _apply.bind(Node.prototype.appendChild);
  1422. Node.prototype.appendChild = function appendChild() {
  1423. '[native code]';
  1424. let res = _appendChild(this, arguments);
  1425. wrapFrames(arguments[0]);
  1426. return res;
  1427. };
  1428.  
  1429. // wrap API in iframe objects created with innerHTML of element on page
  1430. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  1431. let _set_innerHTML = _apply.bind(_innerHTML.set);
  1432. _innerHTML.set = function() {
  1433. _set_innerHTML(this, arguments);
  1434. if (_document.contains(this))
  1435. wrapFrames(this);
  1436. };
  1437. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  1438.  
  1439. wrapAPI(win);
  1440. }
  1441.  
  1442. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1443. scriptLander(
  1444. () => {
  1445. // onerror callback blacklist
  1446. let masks = [],
  1447. blockAll = /(^|\.)(((a-dot-)?kinozal-tv|rutracker-org)\.appspot\.com)$/,
  1448. isBlocked = url => masks.some(mask => mask.test(url)) || blockAll.test(location.hostname);
  1449. for (let filter of [// blacklist
  1450. '/fuckadblock/', '/fuckadblock.',
  1451. '||185.87.50.147^',
  1452. '||10root25.website^', '||24video.xxx^',
  1453. '||adlabs.ru^', '||adspayformymortgage.win^', '||amgload.net^', '||aviabay.ru^',
  1454. '||bgrndi.com^', '||brokeloy.com^',
  1455. '||cdnjs-aws.ru^','||cnamerutor.ru^',
  1456. '||directadvert.ru^', '||dsn-fishki.ru^', '||docfilms.info^', '||dreadfula.ru^',
  1457. '||et-code.ru^', '||etcodes.com^',
  1458. '||franecki.net^', '||film-doma.ru^',
  1459. '||free-torrent.org^', '||free-torrent.pw^',
  1460. '||free-torrents.org^', '||free-torrents.pw^',
  1461. '||game-torrent.info^', '||gocdn.ru^',
  1462. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1463. '||kiev.ua^', '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1464. '||klcheck.com^', '||kuveres.com^',
  1465. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1466. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1467. '||nickhel.com^',
  1468. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1469. '||piguiqproxy.com^', '||pkpojhc.com^',
  1470. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1471. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1472. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1473. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1474. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||trustjs.net^', '||ttarget.ru^',
  1475. '||utarget.ru^',
  1476. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1477. '||xxuhter.ru^',
  1478. '||yuiout.online^',
  1479. '||zmctrack.net^', '||zoom-film.ru^'])
  1480. masks.push(new RegExp(
  1481. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1482. .replace(/\*/g, '.*?')
  1483. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  1484. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  1485. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^/.]+\\.)*?'),
  1486. 'i'));
  1487. // main script
  1488. deepWrapAPI(root => {
  1489. let _call = root.Function.prototype.call,
  1490. _defineProperty = root.Object.defineProperty,
  1491. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor;
  1492. onerror: {
  1493. // 'onerror' handler for scripts from blacklisted sources
  1494. let scriptMap = new WeakMap();
  1495. let _Reflect_apply = root.Reflect.apply,
  1496. _HTMLScriptElement = root.HTMLScriptElement,
  1497. _HTMLImageElement = root.HTMLImageElement;
  1498. let _get_tagName = _call.bind(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1499. _get_scr_src = _call.bind(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1500. _get_img_src = _call.bind(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1501. let _get_src = node => {
  1502. if (node instanceof _HTMLScriptElement)
  1503. return _get_scr_src(node);
  1504. if (node instanceof _HTMLImageElement)
  1505. return _get_img_src(node);
  1506. return void 0
  1507. };
  1508. let _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1509. _set_onerror = _call.bind(_onerror.set);
  1510. _onerror.get = function() {
  1511. return scriptMap.get(this) || null;
  1512. };
  1513. _onerror.set = function(callback) {
  1514. if (typeof callback !== 'function') {
  1515. scriptMap.delete(this);
  1516. _set_onerror(this, callback);
  1517. return;
  1518. }
  1519. scriptMap.set(this, callback);
  1520. _set_onerror(this, function() {
  1521. let src = _get_src(this);
  1522. if (isBlocked(src)) {
  1523. _console.warn(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1524. return;
  1525. }
  1526. _Reflect_apply(scriptMap.get(this), this, arguments);
  1527. });
  1528. };
  1529. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1530. }
  1531. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1532. WSWrap: { // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1533. if (true /*/Maxthon/.test(navigator.appVersion) ||
  1534. 'InstallTrigger' in win && 'StopIteration' in win*/) {
  1535. let _ws = _getOwnPropertyDescriptor(root, 'WebSocket');
  1536. if (!_ws)
  1537. break WSWrap;
  1538. _ws.value = new Proxy(_ws.value, {
  1539. construct: (ws, args) => {
  1540. if (isBlocked(args[0])) {
  1541. _console.log('Blocked WS connection:', args[0]);
  1542. return {};
  1543. }
  1544. return new ws(...args);
  1545. }
  1546. });
  1547. _defineProperty(root, 'WebSocket', _ws);
  1548. }
  1549. }
  1550. untrustedClick: {
  1551. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1552. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1553. let _dispatchEvent = _call.bind(root.EventTarget.prototype.dispatchEvent);
  1554. root.EventTarget.prototype.dispatchEvent = function dispatchEvent(e) {
  1555. if (!e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1556. !this.parentNode && this.tagName === 'A' && this.target[0] === '_') {
  1557. _console.log('Blocked dispatching a click event on a parentless anchor:', this);
  1558. return;
  1559. }
  1560. return _dispatchEvent(this, ...arguments);
  1561. };
  1562. }
  1563. // XHR Wrapper
  1564. let _proto = void 0;
  1565. try {
  1566. _proto = root.XMLHttpRequest.prototype;
  1567. } catch(ignore) {
  1568. return;
  1569. };
  1570. // blacklist of domains where all third-party requests are ignored
  1571. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1572. // highly suspicious URLs
  1573. let suspicious = /^(https?:)?\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1574. let on_get_ban = /^(https?:)?\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+)$/i;
  1575. let on_post_ban = /^(https?:)?\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1576. let yandex_direct = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/((images|weather)\/[a-z0-9/_-]{40,}|jstracer?|j?clck\/.*|set\/s\/rsya-tag-users\/data(\?.*)?|static\/main\.js(\?.*)?)$/i;
  1577. let more_y_direct = /^(https?:)?\/\/([^.]+\.)??(echo\.msk\.ru|liveinternet\.ru|razlozhi\.ru)\/.{290,}/i;
  1578. let whitelist = /^(https?:)?\/\/yandex\.ru\/yobject$/;
  1579.  
  1580. function checkRequest(fname, method, url) {
  1581. if ((isBlocked(url) ||
  1582. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1583. method === 'GET' && on_get_ban.test(url) ||
  1584. method === 'POST' && on_post_ban.test(url) ||
  1585. yandex_direct.test(url) || more_y_direct.test(url)) && !whitelist.test(url)) {
  1586. _console.warn(`Blocked ${fname} ${method} request:`, url);
  1587. return true;
  1588. }
  1589. if (suspicious.test(url))
  1590. _console.warn(`Suspicious ${fname} ${method} request:`, url);
  1591. return false;
  1592. }
  1593.  
  1594. let xhrStopList = new WeakSet();
  1595. let _open = root.Function.prototype.apply.bind(_proto.open);
  1596. _proto.open = function open() {
  1597. '[native code]';
  1598. if (checkRequest('xhr', ...arguments)) {
  1599. xhrStopList.add(this);
  1600. return;
  1601. }
  1602. return _open(this, arguments);
  1603. };
  1604. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1605. name => {
  1606. let func = _proto[name];
  1607. _proto[name] = function(...args) {
  1608. return xhrStopList.has(this) ? null : func.apply(this, args);
  1609. };
  1610. }
  1611. );
  1612. // simulate readyState === 1 for blocked requests
  1613. let _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1614. let _get_readyState = root.Function.prototype.apply.bind(_readyState.get);
  1615. _readyState.get = function() {
  1616. return xhrStopList.has(this) ? 1 : _get_readyState(this, arguments);
  1617. }
  1618. Object.defineProperty(_proto, 'readyState', _readyState);
  1619.  
  1620. let _fetch = root.Function.prototype.apply.bind(root.fetch);
  1621. root.fetch = function fetch() {
  1622. '[native code]';
  1623. let url = arguments[0];
  1624. let method = arguments[1] ? arguments[1].method : void 0;
  1625. if (arguments[0] instanceof Request) {
  1626. method = url.method;
  1627. url = url.url;
  1628. }
  1629. if (checkRequest('fetch', method, url))
  1630. return new Promise(() => null);
  1631. return _fetch(root, arguments);
  1632. };
  1633.  
  1634. let _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1635. let _script_src_set = root.Function.prototype.apply.bind(_script_src.set);
  1636. _script_src.set = function(src) {
  1637. return checkRequest('set', 'script.src', src) || _script_src_set(this, arguments);
  1638. };
  1639. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1640. });
  1641.  
  1642. win.stop = () => {
  1643. _console.warn('window.stop() ...y tho?');
  1644. for (let sheet of _document.styleSheets)
  1645. if (sheet.disabled) {
  1646. sheet.disabled = false;
  1647. _console.log('Re-enabled:', sheet);
  1648. }
  1649. }
  1650. }, deepWrapAPI
  1651. );
  1652.  
  1653. // === Helper functions ===
  1654.  
  1655. // function to search and remove nodes by content
  1656. // selector - standard CSS selector to define set of nodes to check
  1657. // words - regular expression to check content of the suspicious nodes
  1658. // params - object with multiple extra parameters:
  1659. // .log - display log in the console
  1660. // .hide - set display to none instead of removing from the page
  1661. // .parent - parent node to remove if content is found in the child node
  1662. // .siblings - number of simling nodes to remove (excluding text nodes)
  1663. let scRemove = (node) => node.parentNode.removeChild(node);
  1664. let scHide = function(node) {
  1665. let style = _getAttribute(node, 'style') || '',
  1666. hide = ';display:none!important;';
  1667. if (style.indexOf(hide) < 0)
  1668. _setAttribute(node, 'style', style + hide);
  1669. };
  1670.  
  1671. function scissors (selector, words, scope, params) {
  1672. let logger = (...args) => { if (params.log) _console.log(...args) };
  1673. if (!scope.contains(_document.body))
  1674. logger('[s] scope', scope);
  1675. let remFunc = (params.hide ? scHide : scRemove),
  1676. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1677. toRemove = [],
  1678. siblings;
  1679. for (let node of scope.querySelectorAll(selector)) {
  1680. // drill up to a parent node if specified, break if not found
  1681. if (params.parent) {
  1682. let old = node;
  1683. node = node.closest(params.parent);
  1684. if (node === null || node.contains(scope)) {
  1685. logger('[s] went out of scope with', old);
  1686. continue;
  1687. }
  1688. }
  1689. logger('[s] processing', node);
  1690. if (toRemove.includes(node))
  1691. continue;
  1692. if (words.test(node.innerHTML)) {
  1693. // skip node if already marked for removal
  1694. logger('[s] marked for removal');
  1695. toRemove.push(node);
  1696. // add multiple nodes if defined more than one sibling
  1697. siblings = Math.abs(params.siblings) || 0;
  1698. while (siblings) {
  1699. node = node[iterFunc];
  1700. if (!node) break; // can't go any further - exit
  1701. logger('[s] adding sibling node', node);
  1702. toRemove.push(node);
  1703. siblings -= 1;
  1704. }
  1705. }
  1706. }
  1707. let toSkip = [];
  1708. for (let node of toRemove)
  1709. if (!toRemove.every(other => other === node || !node.contains(other)))
  1710. toSkip.push(node);
  1711. if (toRemove.length)
  1712. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1713. for (let node of toRemove) if (!toSkip.includes(node))
  1714. remFunc(node);
  1715. }
  1716.  
  1717. // function to perform multiple checks if ads inserted with a delay
  1718. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1719. // also does 1 extra check when a page completely loads
  1720. // selector and words - passed dow to scissors
  1721. // params - object with multiple extra parameters:
  1722. // .log - display log in the console
  1723. // .root - selector to narrow down scope to scan;
  1724. // .observe - if true then check will be performed continuously;
  1725. // Other parameters passed down to scissors.
  1726. function gardener(selector, words, params) {
  1727. let logger = (...args) => { if (params.log) _console.log(...args) };
  1728. params = params || {};
  1729. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1730. let scope;
  1731. let globalScope = [_de];
  1732. let domLoaded = false;
  1733. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1734. let onevent = e => {
  1735. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1736. for (let node of scope)
  1737. scissors(selector, words, node, params);
  1738. };
  1739. let repeater = n => {
  1740. if (!domLoaded && n) {
  1741. setTimeout(repeater, 500, n - 1);
  1742. scope = getScope(params.root);
  1743. if (!scope) // exit if the root element is not present on the page
  1744. return 0;
  1745. onevent({type: 'Repeater'});
  1746. }
  1747. };
  1748. repeater(20);
  1749. _document.addEventListener(
  1750. 'DOMContentLoaded', (e) => {
  1751. domLoaded = true;
  1752. // narrow down scope to a specific element
  1753. scope = getScope(params.root);
  1754. if (!scope) // exit if the root element is not present on the page
  1755. return 0;
  1756. logger('[g] scope', scope);
  1757. // add observe mode if required
  1758. if (params.observe) {
  1759. let params = { childList:true, subtree: true };
  1760. let observer = new MutationObserver(
  1761. function(ms) {
  1762. for (let m of ms)
  1763. if (m.addedNodes.length)
  1764. onevent(m);
  1765. }
  1766. );
  1767. for (let node of scope)
  1768. observer.observe(node, params);
  1769. logger('[g] observer enabled');
  1770. }
  1771. onevent(e);
  1772. }, false);
  1773. // wait for a full page load to do one extra cut
  1774. win.addEventListener('load', onevent, false);
  1775. }
  1776.  
  1777. // wrap popular methods to open a new tab to catch specific behaviours
  1778. function createWindowOpenWrapper(openFunc) {
  1779. let _createElement = _Document.createElement,
  1780. _appendChild = _Element.appendChild,
  1781. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1782.  
  1783. let nt = new nullTools();
  1784. fakeNative(openFunc);
  1785.  
  1786. let parser = _createElement.call(_document, 'a');
  1787. let openWhitelist = (url, parent) => {
  1788. parser.href = url;
  1789. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1790. parent.hostname === 'radikal.ru' && url === void 0;
  1791. };
  1792.  
  1793. let redefineOpen = (root) => {
  1794. if ('open' in root) {
  1795. let _open = root.open.bind(root);
  1796. nt.define(root, 'open', (...args) => {
  1797. if (openWhitelist(args[0], location)) {
  1798. _console.log('Whitelisted popup:', ...args);
  1799. return _open(...args);
  1800. }
  1801. return openFunc(...args);
  1802. });
  1803. }
  1804. };
  1805. redefineOpen(win);
  1806.  
  1807. function createElement() {
  1808. '[native code]';
  1809. let el = _createElement.apply(this, arguments);
  1810. // redefine window.open in first-party frames
  1811. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1812. el.addEventListener('load', (e) => {
  1813. try {
  1814. redefineOpen(e.target.contentWindow);
  1815. } catch(ignore) {}
  1816. }, false);
  1817. return el;
  1818. }
  1819. fakeNative(createElement);
  1820.  
  1821. let redefineCreateElement = (obj) => {
  1822. for (let root of [obj.document, _Document]) if ('createElement' in root)
  1823. nt.define(root, 'createElement', createElement);
  1824. };
  1825. redefineCreateElement(win);
  1826.  
  1827. // wrap window.open in newly added first-party frames
  1828. _Element.appendChild = function appendChild() {
  1829. '[native code]';
  1830. let el = _appendChild.apply(this, arguments);
  1831. if (el instanceof HTMLIFrameElement)
  1832. try {
  1833. redefineOpen(el.contentWindow);
  1834. redefineCreateElement(el.contentWindow);
  1835. } catch(ignore) {}
  1836. return el;
  1837. };
  1838. fakeNative(_Element.appendChild);
  1839. }
  1840.  
  1841. // Function to catch and block various methods to open a new window with 3rd-party content.
  1842. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1843. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1844. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1845. // node or simply a link with piece of javascript code in the HREF attribute.
  1846. function preventPopups() {
  1847. // call sandbox-me if in iframe and not whitelisted
  1848. if (inIFrame) {
  1849. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1850. return;
  1851. }
  1852.  
  1853. scriptLander(() => {
  1854. let nt = new nullTools({log:true});
  1855. let open = (...args) => {
  1856. '[native code]';
  1857. _console.warn('Site attempted to open a new window', ...args);
  1858. return {
  1859. document: nt.proxy({
  1860. write: nt.func({}, 'write'),
  1861. writeln: nt.func({}, 'writeln')
  1862. }),
  1863. location: nt.proxy({})
  1864. };
  1865. };
  1866.  
  1867. createWindowOpenWrapper(open);
  1868.  
  1869. _console.log('Popup prevention enabled.');
  1870. }, nullTools, createWindowOpenWrapper);
  1871. }
  1872.  
  1873. // Helper function to close background tab if site opens itself in a new tab and then
  1874. // loads a 3rd-party page in the background one (thus performing background redirect).
  1875. function preventPopunders() {
  1876. // create "close_me" event to call high-level window.close()
  1877. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1878. let callClose = () => {
  1879. _console.log('close call');
  1880. window.close();
  1881. };
  1882. window.addEventListener(eventName, callClose, true);
  1883.  
  1884. scriptLander(() => {
  1885. // get host of a provided URL with help of an anchor object
  1886. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1887. let parseURL = _document.createElement('A');
  1888. let getHost = url => {
  1889. parseURL.href = url;
  1890. return parseURL.hostname
  1891. };
  1892. // site went to a new tab and attempts to unload
  1893. // call for high-level close through event
  1894. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1895. // check is URL local or goes to different site
  1896. let isLocal = (url) => {
  1897. if (url === location.pathname || url === location.href)
  1898. return true; // URL points to current pathname or full address
  1899. let host = getHost(url);
  1900. let site = location.hostname;
  1901. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1902. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1903. };
  1904.  
  1905. let _open = window.open.bind(window);
  1906. let open = (...args) => {
  1907. '[native code]';
  1908. let url = args[0];
  1909. if (url && isLocal(url))
  1910. window.addEventListener('beforeunload', closeWindow, true);
  1911. return _open(...args);
  1912. };
  1913.  
  1914. createWindowOpenWrapper(open);
  1915.  
  1916. _console.log("Background redirect prevention enabled.");
  1917. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1918. }
  1919.  
  1920. // Mix between check for popups and popunders
  1921. // Significantly more agressive than both and can't be used as universal solution
  1922. function preventPopMix() {
  1923. if (inIFrame) {
  1924. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1925. return;
  1926. }
  1927.  
  1928. // create "close_me" event to call high-level window.close()
  1929. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1930. let callClose = () => {
  1931. _console.log('close call');
  1932. window.close();
  1933. };
  1934. window.addEventListener(eventName, callClose, true);
  1935.  
  1936. scriptLander(() => {
  1937. let _open = window.open,
  1938. parseURL = _document.createElement('A');
  1939. // get host of a provided URL with help of an anchor object
  1940. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1941. let getHost = (url) => {
  1942. parseURL.href = url;
  1943. return parseURL.host;
  1944. };
  1945. // site went to a new tab and attempts to unload
  1946. // call for high-level close through event
  1947. let closeWindow = () => {
  1948. _open(window.location,'_self');
  1949. window.dispatchEvent(new CustomEvent(eventName, {}));
  1950. };
  1951. // check is URL local or goes to different site
  1952. function isLocal(url) {
  1953. let loc = window.location;
  1954. if (url === loc.pathname || url === loc.href)
  1955. return true; // URL points to current pathname or full address
  1956. let host = getHost(url),
  1957. site = loc.host;
  1958. if (host === '')
  1959. return false; // URLs with unusual protocol may have empty 'host'
  1960. if (host.length > site.length)
  1961. [site, host] = [host, site];
  1962. return site.includes(host, site.length - host.length);
  1963. }
  1964.  
  1965. // add check for redirect for 5 seconds, then disable it
  1966. function checkRedirect() {
  1967. window.addEventListener('beforeunload', closeWindow, true);
  1968. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1969. }
  1970.  
  1971. function open(url, name) {
  1972. '[native code]';
  1973. if (url && isLocal(url) && (!name || name === '_blank')) {
  1974. _console.warn('Suspicious local new window', arguments);
  1975. checkRedirect();
  1976. return _open.apply(this, arguments);
  1977. }
  1978. _console.warn('Blocked attempt to open a new window', arguments);
  1979. return {
  1980. document: {
  1981. write: () => {},
  1982. writeln: () => {}
  1983. }
  1984. };
  1985. }
  1986.  
  1987. function clickHandler(e) {
  1988. let link = e.target,
  1989. url = link.href||'';
  1990. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1991. _console.log('Link', link, 'were created dinamically, but looks fine.');
  1992. return true;
  1993. }
  1994. if (isLocal(url) && link.target === '_blank') {
  1995. _console.log('Suspicious local link', link);
  1996. checkRedirect();
  1997. return;
  1998. }
  1999. _console.log('Blocked suspicious click on a link', link);
  2000. e.stopPropagation();
  2001. e.preventDefault();
  2002. }
  2003.  
  2004. createWindowOpenWrapper(open, clickHandler);
  2005.  
  2006. _console.log("Mixed popups prevention enabled.");
  2007. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2008. }
  2009. // External listener for case when site known to open popups were loaded in iframe
  2010. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2011. // Some sites replace frame's window.location with data-url to run in clean context
  2012. if (!inIFrame) window.addEventListener(
  2013. 'message', function(e) {
  2014. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2015. return;
  2016. let src = e.data.href;
  2017. for (let frame of _document.querySelectorAll('iframe'))
  2018. if (frame.contentWindow === e.source) {
  2019. if (frame.hasAttribute('sandbox')) {
  2020. if (!frame.sandbox.contains('allow-popups'))
  2021. return; // exit frame since it's already sandboxed and popups are blocked
  2022. // remove allow-popups if frame already sandboxed
  2023. frame.sandbox.remove('allow-popups');
  2024. } else
  2025. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2026. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2027. // but to apply content must be reloaded and this script will re-apply it in the result
  2028. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2029. _console.log('Disallowed popups from iframe', frame);
  2030.  
  2031. // reload frame content to apply restrictions
  2032. if (!src) {
  2033. src = frame.src;
  2034. _console.log('Unable to get current iframe location, reloading from src', src);
  2035. } else
  2036. _console.log('Reloading iframe with URL', src);
  2037. frame.src = 'about:blank';
  2038. frame.src = src;
  2039. }
  2040. }, false
  2041. );
  2042.  
  2043. let evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/;
  2044. let evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2045. function selectiveEval(...patterns) {
  2046. if (patterns.length === 0)
  2047. patterns.push(evalPatternGeneric);
  2048. scriptLander(() => {
  2049. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2050. if (!_eval_def || !_eval_def.value) {
  2051. _console.warn('Unable to wrap window.eval.', _eval_def);
  2052. return;
  2053. }
  2054. let _eval_val = _eval_def.value;
  2055. _eval_def.value = function(...args) {
  2056. if (patterns.some(pattern => pattern.test(args[0]))) {
  2057. _console.warn(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2058. return null;
  2059. }
  2060. try {
  2061. return _eval_val.apply(this, args);
  2062. } catch(e) {
  2063. _console.log('Crash source:', args[0]);
  2064. throw e;
  2065. }
  2066. };
  2067. Object.defineProperty(win, 'eval', _eval_def);
  2068. });
  2069. }
  2070.  
  2071. // hides cookies by pattern and attempts to remove them if they already set
  2072. // also prevents setting new versions of such cookies
  2073. function selectiveCookies(scPattern, scPaths = []) {
  2074. scriptLander(() => {
  2075. let ga = '_g(at?|id)|__utm[a-z]'; // Google Analytics Cookies
  2076. scPattern = new RegExp(`(^|;\\s?)(${scPattern}|${ga})($|=)`);
  2077. if (isFirefox && scPaths.length)
  2078. scPaths.forEach((path, id) => scPaths[id] = `${path}/`);
  2079. scPaths.push('/');
  2080. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  2081. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2082. if (_cookie) {
  2083. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2084. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2085. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2086. let expireAge = '-99999999';
  2087. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2088. let expireAttempted = {};
  2089. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2090. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2091. let expire = (cookie, that) => {
  2092. let domain = that.location.hostname.split('.'),
  2093. name = cookie.replace(/=.*/,'');
  2094. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2095. while (domain.length > 1) {
  2096. try {
  2097. scPaths.forEach(
  2098. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2099. );
  2100. } catch(e) { _console.warn(e); }
  2101. domain.shift();
  2102. }
  2103. expireAttempted[name] = true;
  2104. _console.log('Removing existing cookie:', cookie);
  2105. };
  2106. // skip setting unwanted cookies
  2107. _cookie.set = function(value) {
  2108. if (scPattern.test(value)) {
  2109. _console.warn('Ignored cookie:', value);
  2110. // try to remove same cookie if it already exists using exact values from the set string
  2111. if (scPattern.test(_get_cookie(this))) {
  2112. let parts = value.split(/;\s?/),
  2113. name = parts[0].replace(/=.*/,''),
  2114. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2115. skip = [name, 'expires', 'Max-Age'];
  2116. for (let part of parts)
  2117. if (!skip.includes(part.replace(/=.*/,'')))
  2118. newParts.push(part);
  2119. try {
  2120. _set_cookie(this, newParts.join(';'));
  2121. } catch(e) { _console.warn(e); }
  2122. _console.log('Removing existing cookie:', name);
  2123. }
  2124. return;
  2125. }
  2126. return _set_cookie(this, value);
  2127. };
  2128. // hide unwanted cookies from site
  2129. _cookie.get = function() {
  2130. let res = _get_cookie(this);
  2131. if (scPattern.test(res)) {
  2132. let stack = [];
  2133. for (let cookie of res.split(/;\s?/))
  2134. if (!scPattern.test(cookie))
  2135. stack.push(cookie);
  2136. else {
  2137. let name = cookie.replace(/=.*/,'');
  2138. if (expireAttempted[name]) {
  2139. _console.log('Unable to expire:', cookie);
  2140. expireAttempted[name] = false;
  2141. }
  2142. if (!(name in expireAttempted))
  2143. expire(cookie, this);
  2144. }
  2145. res = stack.join('; ');
  2146. }
  2147. return res;
  2148. };
  2149. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2150. }
  2151. _console.log('Active cookies:', document.cookie);
  2152. }, `let scPattern = "${scPattern}", scPaths = ${scPaths}, isFirefox = ${isFirefox};`);
  2153. }
  2154.  
  2155. /*{ // simple toString wrapper, might be useful to prevent detection
  2156. '[native code]';
  2157. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2158. let baseText = Function.prototype.toString.toString();
  2159. let protect = new WeakSet();
  2160. protect.add(_Document.createElement);
  2161. protect.add(_Node.appendChild);
  2162. protect.add(_Node.removeChild);
  2163. win.Function.prototype.toString = function() {
  2164. if (protect.has(this))
  2165. return baseText.replace('toString', this.name);
  2166. return _toString(this);
  2167. };
  2168. protect.add(Function.prototype.toString);
  2169. }*/
  2170.  
  2171. // Locates a node with specific text in Russian
  2172. // Uses table of substitutions for similar letters
  2173. let selectNodeByTextContent = (()=> {
  2174. let subs = {
  2175. // english & greek
  2176. 'А': 'AΑ', 'В': 'BΒ', 'Г':'Γ',
  2177. 'Е': 'EΕ', 'З': '3', 'К':'KΚ',
  2178. 'М': 'MΜ', 'Н': 'HΗ', 'О':'OΟ',
  2179. 'П': 'Π', 'Р': 'PΡ', 'С':'C',
  2180. 'Т': 'T', 'Ф': 'Φ', 'Х':'XΧ'
  2181. }
  2182. let regExpBuilder = text => new RegExp(
  2183. text.toUpperCase()
  2184. .split('')
  2185. .map(function(e){
  2186. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2187. })
  2188. .join(''),
  2189. 'i');
  2190. let reMap = {};
  2191. return (re, opts = { root: _document.body }) => {
  2192. if (!re.test) {
  2193. if (!reMap[re])
  2194. reMap[re] = regExpBuilder(re);
  2195. re = reMap[re];
  2196. }
  2197.  
  2198. for (let child of opts.root.children)
  2199. if (re.test(child.textContent)) {
  2200. if (opts.shallow)
  2201. return child;
  2202. opts.root = child;
  2203. return selectNodeByTextContent(re, opts) || child;
  2204. }
  2205. }
  2206. })();
  2207.  
  2208. // === Scripts for specific domains ===
  2209.  
  2210. let scripts = {};
  2211. // prevent popups and redirects block
  2212. // Popups
  2213. scripts.preventPopups = {
  2214. other: [
  2215. 'biqle.ru',
  2216. 'chaturbate.com',
  2217. 'dfiles.ru',
  2218. 'eporner.eu',
  2219. 'hentaiz.org',
  2220. 'mirrorcreator.com',
  2221. 'online-multy.ru',
  2222. 'radikal.ru', 'rumedia.ws',
  2223. 'tapehub.tech', 'thepiratebay.org',
  2224. 'unionpeer.com',
  2225. 'zippyshare.com'
  2226. ],
  2227. now: preventPopups
  2228. };
  2229. // Popunders (background redirect)
  2230. scripts.preventPopunders = {
  2231. other: [
  2232. 'lostfilm-online.ru',
  2233. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2234. 'perfectgirls.net'
  2235. ],
  2236. now: preventPopunders
  2237. };
  2238. // PopMix (both types of popups encountered on site)
  2239. scripts['openload.co'] = {
  2240. other: ['oload.tv', 'oload.info'],
  2241. now: () => {
  2242. let nt = new nullTools();
  2243. nt.define(win, 'CNight', win.CoinHive);
  2244. if (location.pathname.startsWith('/embed/')) {
  2245. nt.define(win, 'BetterJsPop', {
  2246. add: ((a, b) => _console.warn('BetterJsPop.add', a, b)),
  2247. config: ((o) => _console.warn('BetterJsPop.config', o)),
  2248. Browser: { isChrome: true }
  2249. });
  2250. nt.define(win, 'isSandboxed', nt.func(null));
  2251. nt.define(win, 'adblock', false);
  2252. nt.define(win, 'adblock2', false);
  2253. } else preventPopMix();
  2254. }
  2255. };
  2256. scripts['turbobit.net'] = preventPopMix;
  2257.  
  2258. scripts['tapochek.net'] = () => {
  2259. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2260. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2261. let _appendChild_value = _appendChild.value;
  2262. _appendChild.value = function appendChild(node) {
  2263. if (this === _document.body)
  2264. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2265. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2266. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2267. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2268. throw '...eenope!';
  2269. return _appendChild_value.apply(this, arguments);
  2270. };
  2271. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2272.  
  2273. // disable window focus tricks and changing location
  2274. let focusHandlerName = /\WfocusAchieved\(/
  2275. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2276. let _setInterval = win.setInterval;
  2277. win.setInterval = (...args) => {
  2278. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2279. _console.log('skip setInterval for', ...args);
  2280. return -1;
  2281. }
  2282. return _setInterval(...args);
  2283. };
  2284. let _addEventListener = win.addEventListener;
  2285. win.addEventListener = function(...args) {
  2286. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2287. _console.log('skip addEventListener for', ...args);
  2288. return void 0;
  2289. }
  2290. return _addEventListener.apply(this, args);
  2291. };
  2292.  
  2293. // generic popup prevention
  2294. preventPopups();
  2295. };
  2296.  
  2297. scripts['rustorka.com'] = {
  2298. other: ['rustorka.club', 'rustorka.lib', 'rustorka.net'],
  2299. now: () => {
  2300. selectiveEval(evalPatternGeneric, /antiadblock/);
  2301. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2302. scriptLander(() => {
  2303. // wrap window.open to catch a popup if it triggers
  2304. win.open = (...args) => {
  2305. _console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2306. location.replace(location.href);
  2307. return null;
  2308. };
  2309. window.addEventListener('DOMContentLoaded', () => {
  2310. let link = void 0;
  2311. _document.body.addEventListener('mousedown', e => {
  2312. link = e.target.closest('a, select, #fancybox-title-wrap');
  2313. }, false);
  2314. let _open = window.open.bind(window);
  2315. let _getAttribute = Function.prototype.call.bind(_Element.getAttribute);
  2316. win.open = (...args) => {
  2317. let url = args[0];
  2318. if (link instanceof HTMLAnchorElement) {
  2319. // third-party post links
  2320. let href = _getAttribute(link, 'href');
  2321. if (link.classList.contains('postLink') &&
  2322. !link.matches(`a[href*="${location.hostname}"]`) &&
  2323. (href === url || link.href === url))
  2324. return _open(...args);
  2325. // onclick # links
  2326. if (href === '#' && /window\.open/.test(_getAttribute(link, 'onclick')))
  2327. return _open(...args);
  2328. // force local links to load in the current window
  2329. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2330. location.assign(href);
  2331. }
  2332. // list of image hostings under upload picture button (new comment)
  2333. if (link instanceof HTMLSelectElement &&
  2334. !url.includes(location.hostname) &&
  2335. link.value === url)
  2336. return _open(...args);
  2337. // open screenshot in a new window
  2338. if (link instanceof HTMLSpanElement &&
  2339. link.id === 'fancybox-title-wrap')
  2340. return _open(...args);
  2341. // looks like tabunder
  2342. if (link === null && url === location.href)
  2343. location.replace(url); // reload current page
  2344. // other cases
  2345. _console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2346. return {};
  2347. };
  2348. }, true);
  2349. }, nullTools)
  2350. }
  2351. };
  2352.  
  2353. // = other ======================================================================================
  2354. scripts['1tv.ru'] = {
  2355. other: ['mediavitrina.ru'],
  2356. now: () => scriptLander(() => {
  2357. let nt = new nullTools();
  2358. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2359. let disablePlugins = {
  2360. 'antiblock': false,
  2361. 'stat1tv': false
  2362. };
  2363. let _EUMPConfig = void 0;
  2364. let _EUMPConfig_set = x => {
  2365. if (x.plugins) {
  2366. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2367. _console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2368. }
  2369. _EUMPConfig = x;
  2370. };
  2371. if ('EUMPConfig' in win)
  2372. _EUMPConfig_set(win.EUMPConfig);
  2373. Object.defineProperty(win, 'EUMPConfig', {
  2374. enumerable: true,
  2375. get: () => _EUMPConfig,
  2376. set: _EUMPConfig_set
  2377. });
  2378. }, nullTools)
  2379. };
  2380.  
  2381. scripts['2picsun.ru'] = {
  2382. other: [
  2383. 'pics2sun.ru', '3pics-img.ru'
  2384. ],
  2385. now: () => {
  2386. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2387. }
  2388. };
  2389.  
  2390. scripts['4pda.ru'] = {
  2391. now: () => {
  2392. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2393. let isForum = location.pathname.startsWith('/forum/'),
  2394. remove = node => (node && node.parentNode.removeChild(node)),
  2395. hide = node => (node && (node.style.display = 'none'));
  2396.  
  2397. // clean a page
  2398. window.addEventListener(
  2399. 'DOMContentLoaded', function() {
  2400. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2401. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2402.  
  2403. HeaderAds: {
  2404. // hide ads above HEADER
  2405. let header = _document.querySelector('.drop-search');
  2406. if (!header) {
  2407. _console.warn('Unable to locate header element');
  2408. break HeaderAds;
  2409. }
  2410. header = header.parentNode.parentNode;
  2411. for (let itm of header.parentNode.children)
  2412. if (itm !== header)
  2413. hide(itm);
  2414. else break;
  2415. }
  2416.  
  2417. if (isForum) {
  2418. let itm = _document.querySelector('#logostrip');
  2419. if (itm)
  2420. remove(itm.parentNode.nextSibling);
  2421. // clear background in the download frame
  2422. if (location.pathname.startsWith('/forum/dl/')) {
  2423. let setBackground = node => _setAttribute(
  2424. node,
  2425. 'style', (_getAttribute(node, 'style') || '') +
  2426. ';background-color:#4ebaf6!important'
  2427. );
  2428. setBackground(_document.body);
  2429. for (let itm of _document.querySelectorAll('body > div'))
  2430. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2431. remove(itm);
  2432. else
  2433. setBackground(itm);
  2434. }
  2435. // exist from DOMContentLoaded since the rest is not for forum
  2436. return;
  2437. }
  2438.  
  2439. FixNavMenu: {
  2440. // restore DevDB link in the navigation
  2441. let itm = _document.querySelector('#nav li a[href$="/devdb/"]')
  2442. if (!itm) {
  2443. _console.warn('Unable to locate navigation menu');
  2444. break FixNavMenu;
  2445. }
  2446. itm.closest('li').style.display = 'block';
  2447. // hide ad link from the navigation
  2448. hide(_document.querySelector('#nav li a[data-dotrack]'));
  2449. }
  2450. SidebarAds: {
  2451. // remove ads from sidebar
  2452. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child');
  2453. if (!aside.length) {
  2454. _console.warn('Unable to locate sidebar');
  2455. break SidebarAds;
  2456. }
  2457. let post;
  2458. for (let side of aside) {
  2459. _console.log('Processing potential sidebar:', side);
  2460. for (let itm of Array.from(side.children)) {
  2461. post = itm.classList.contains('post');
  2462. if (itm.querySelector('iframe') && !post)
  2463. remove(itm);
  2464. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2465. hide(itm);
  2466. }
  2467. }
  2468. }
  2469.  
  2470. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2471.  
  2472. let extra = 'background-image:none!important;background-color:transparent!important',
  2473. fakeStyles = new WeakMap(),
  2474. styleProxy = {
  2475. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2476. set: function(target, prop, value) {
  2477. let fakeStyle = fakeStyles.get(target);
  2478. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2479. return true;
  2480. }
  2481. };
  2482. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2483. if (!(itm.offsetWidth > 0.95 * width() &&
  2484. itm.offsetHeight > 0.85 * height()))
  2485. continue;
  2486. if (itm.tagName !== 'A') {
  2487. fakeStyles.set(itm.style, {
  2488. 'backgroundImage': itm.style.backgroundImage,
  2489. 'backgroundColor': itm.style.backgroundColor
  2490. });
  2491.  
  2492. try {
  2493. Object.defineProperty(itm, 'style', {
  2494. value: new Proxy(itm.style, styleProxy),
  2495. enumerable: true
  2496. });
  2497. } catch (e) {
  2498. _console.log('Unable to protect style property.', e);
  2499. }
  2500.  
  2501. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2502. }
  2503. if (itm.tagName === 'A')
  2504. _setAttribute(itm, 'style', 'display:none!important');
  2505. }
  2506. }
  2507. );
  2508. }
  2509. };
  2510.  
  2511. scripts['adhands.ru'] = () => scriptLander(() => {
  2512. let nt = new nullTools();
  2513. try {
  2514. let _adv;
  2515. Object.defineProperty(win, 'adv', {
  2516. get: () => _adv,
  2517. set: (v) => {
  2518. _console.log('Blocked advert on adhands.ru.');
  2519. nt.define(v, 'advert', '');
  2520. _adv = v;
  2521. }
  2522. });
  2523. } catch (ignore) {
  2524. if (!win.adv)
  2525. _console.log('Unable to locate advert on adhands.ru.');
  2526. else {
  2527. _console.log('Blocked advert on adhands.ru.');
  2528. nt.define(win.adv, 'advert', '');
  2529. }
  2530. }
  2531. }, nullTools);
  2532.  
  2533. scripts['all-episodes.tv'] = () => {
  2534. let nt = new nullTools();
  2535. nt.define(win, 'perX1', 2);
  2536. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2537. };
  2538.  
  2539. scripts['allhentai.ru'] = () => {
  2540. selectiveEval();
  2541. preventPopups();
  2542. scriptLander(() => {
  2543. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2544. if (!_onerror)
  2545. return;
  2546. _onerror.set = (...args) => _console.log(args[0].toString());
  2547. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2548. });
  2549. };
  2550.  
  2551. scripts['allmovie.pro'] = {
  2552. other: ['rufilmtv.org'],
  2553. dom: function() {
  2554. // pretend to be Android to make site use different played for ads
  2555. if (isSafari)
  2556. return;
  2557. Object.defineProperty(navigator, 'userAgent', {
  2558. get: function(){
  2559. return 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19';
  2560. },
  2561. enumerable: true
  2562. });
  2563. }
  2564. };
  2565.  
  2566. scripts['anidub-online.ru'] = {
  2567. other: ['anime.anidub.com', 'online.anidub.com'],
  2568. dom: function() {
  2569. if (win.ogonekstart1)
  2570. win.ogonekstart1 = () => _console.log("Fire in the hole!");
  2571. },
  2572. now: () => createStyle([
  2573. '.background {background: none!important;}',
  2574. '.background > script + div,'+
  2575. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2576. '{display:none!important}'
  2577. ])
  2578. };
  2579.  
  2580. scripts['audioportal.su'] = {
  2581. now: () => createStyle('#blink2 { display: none !important }'),
  2582. dom: () => {
  2583. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2584. if (!links) return;
  2585. for (let link of links)
  2586. clickme(link);
  2587. }
  2588. };
  2589.  
  2590. scripts['avito.ru'] = () => selectiveCookies('abp|bltsr|cmtchd|crookie|is_adblock');
  2591.  
  2592. scripts['di.fm'] = () => scriptLander(() => {
  2593. let log = false;
  2594. // wrap global app object to catch registration of specific modules
  2595. let _di = void 0;
  2596. Object.defineProperty(win, 'di', {
  2597. get: () => _di,
  2598. set: vl => {
  2599. if (vl === _di)
  2600. return;
  2601. log && _console.log('di =', vl);
  2602. _di = new Proxy(vl, {
  2603. set: (di, name, vl) => {
  2604. if (vl === di[name])
  2605. return true;
  2606. if (name === 'app') {
  2607. log && _console.log('di.app =', vl);
  2608. if ('module' in vl)
  2609. vl.module = new Proxy(vl.module, {
  2610. apply: (module, that, args) => {
  2611. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2612. let name = args[0];
  2613. log && _console.warn('wrap', name, 'module');
  2614. if (typeof args[1] === 'function')
  2615. args[1] = new Proxy(args[1], {
  2616. apply: (fun, that, args) => {
  2617. if (args[0]) // module object
  2618. args[0].start = () => _console.log('Skipped start of', name);
  2619. return Reflect.apply(fun, that, args);
  2620. }
  2621. });
  2622. }// else log && _console.log('loading module', args[0]);
  2623. if (args[0] === 'Modals') {
  2624. log && _console.warn('wrap', name, 'module');
  2625. if (typeof args[1] === 'function')
  2626. args[1] = new Proxy(args[1], {
  2627. apply: (fun, that, args) => {
  2628. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2629. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2630. let _commands = args[1].commands;
  2631. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2632. apply: (fun, that, args) => {
  2633. for (let name in args[0])
  2634. if (name === 'modal:streaminterrupt' ||
  2635. name === 'modal:midroll')
  2636. args[0][name] = () => _console.log('Skipped', name, 'window');
  2637. delete _commands.setHandlers;
  2638. return Reflect.apply(fun, that, args);
  2639. }
  2640. });
  2641. }
  2642. return Reflect.apply(fun, that, args);
  2643. }
  2644. });
  2645. }
  2646. return Reflect.apply(module, that, args);
  2647. }
  2648. });
  2649. }
  2650. di[name] = vl;
  2651. return true;
  2652. }
  2653. });
  2654. }
  2655. });
  2656. // don't send errorception logs
  2657. Object.defineProperty(win, 'onerror', {
  2658. set: vl => log && _console.warn('Skipped global onerror callback', vl)
  2659. });
  2660. });
  2661.  
  2662. scripts['drive2.ru'] = () => {
  2663. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2664. scriptLander(() => {
  2665. let _d2 = void 0;
  2666. Object.defineProperty(win, 'd2', {
  2667. get: () => _d2,
  2668. set: o => {
  2669. if (o === _d2)
  2670. return true;
  2671. _d2 = new Proxy(o, {
  2672. set: (tgt, prop, val) => {
  2673. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2674. val = () => null;
  2675. tgt[prop] = val;
  2676. return true;
  2677. }
  2678. });
  2679. }
  2680. });
  2681. });
  2682. };
  2683.  
  2684. scripts['echo.msk.ru'] = () => selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  2685.  
  2686. scripts['fastpic.ru'] = () => {
  2687. let nt = new nullTools();
  2688. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2689. nt.define(win, `_0x${'4955'}`, []);
  2690. };
  2691.  
  2692. scripts['fishki.net'] = () => {
  2693. scriptLander(() => {
  2694. let nt = new nullTools();
  2695. let fishki = {};
  2696. nt.define(fishki, 'adv', nt.proxy({
  2697. afterAdblockCheck: nt.func(null),
  2698. refreshFloat: nt.func(null)
  2699. }));
  2700. nt.define(fishki, 'is_adblock', false);
  2701. nt.define(win, 'fishki', fishki);
  2702. }, nullTools);
  2703. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2704. };
  2705.  
  2706. scripts['friends.in.ua'] = () => scriptLander(() => {
  2707. Object.defineProperty(win, 'need_warning', {
  2708. get: () => 0, set: () => null
  2709. });
  2710. });
  2711.  
  2712. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2713.  
  2714. scripts['hdgo.cc'] = {
  2715. other: ['46.30.43.38', 'couber.be'],
  2716. now: () => (new MutationObserver(
  2717. (ms) => {
  2718. let m, node;
  2719. for (m of ms) for (node of m.addedNodes)
  2720. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2721. node.removeAttribute('onerror');
  2722. }
  2723. )).observe(_document.documentElement, { childList:true, subtree: true })
  2724. };
  2725.  
  2726. scripts['gismeteo.ru'] = {
  2727. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2728. now: () => {
  2729. selectiveCookies('ab_[^=]*|bltsr|redirect|_gab');
  2730. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2731. }
  2732. };
  2733.  
  2734. scripts['hdrezka.ag'] = () => {
  2735. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2736. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2737. };
  2738.  
  2739. scripts['hqq.tv'] = () => scriptLander(() => {
  2740. // disable anti-debugging in hqq.tv player
  2741. let isObfuscated = text => /[^a-z0-9]([a-z0-9]{1,2}\.[a-z0-9]{1,2}\(|[a-z0-9]{4}\.[a-z]\(\d+\)|[a-z0-9]\[[a-z0-9]{1,2}\]\[[a-z0-9]{1,2}\])/i.test(text);
  2742. deepWrapAPI(root => {
  2743. // skip obfuscated stuff and a few other calls
  2744. let _setInterval = root.setInterval,
  2745. _setTimeout = root.setTimeout,
  2746. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2747. root.setInterval = (...args) => {
  2748. let fun = args[0];
  2749. if (fun instanceof Function) {
  2750. let text = _toString(fun),
  2751. skip = text.includes('check();') || isObfuscated(text);
  2752. _console.warn('setInterval', text, 'skip', skip);
  2753. if (skip) return -1;
  2754. }
  2755. return _setInterval.apply(this, args);
  2756. };
  2757. let wrappedST = new WeakSet();
  2758. root.setTimeout = (...args) => {
  2759. let fun = args[0];
  2760. if (fun instanceof Function) {
  2761. let text = _toString(fun),
  2762. skip = fun.name === 'check' || isObfuscated(text);
  2763. if (!wrappedST.has(fun)) {
  2764. _console.warn('setTimeout', text, 'skip', skip);
  2765. wrappedST.add(fun);
  2766. }
  2767. if (skip) return;
  2768. }
  2769. return _setTimeout.apply(this, args);
  2770. };
  2771. // skip 'debugger' call
  2772. let _eval = root.eval;
  2773. root.eval = text => {
  2774. if (typeof text === 'string' && text.includes('debugger;')) {
  2775. _console.warn('skip eval', text);
  2776. return;
  2777. }
  2778. _eval(text);
  2779. };
  2780. // Prevent RegExpt + toString trick
  2781. let _proto = void 0;
  2782. try {
  2783. _proto = root.RegExp.prototype;
  2784. } catch(ignore) {
  2785. return;
  2786. }
  2787. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  2788. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  2789. Object.defineProperty(_proto, 'toString', {
  2790. enumerable: _RE_tS.enumerable,
  2791. configurable: _RE_tS.configurable,
  2792. get: () => _RE_tSV,
  2793. set: val => _console.warn('Attempt to change toString for', this, 'with', _toString(val))
  2794. });
  2795. });
  2796. }, deepWrapAPI);
  2797.  
  2798. scripts['hideip.me'] = {
  2799. now: () => scriptLander(() => {
  2800. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  2801. let _set_innerHTML = _innerHTML.set;
  2802. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2803. let _get_innerText = _innerText.get;
  2804. let div = _document.createElement('div');
  2805. _innerHTML.set = function(...args) {
  2806. _set_innerHTML.call(div, args[0].replace('i','a'));
  2807. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2808. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2809. _console.log('Anti-Adblock killed.');
  2810. return true;
  2811. }
  2812. _set_innerHTML.apply(this, args);
  2813. };
  2814. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  2815. Object.defineProperty(win, 'adblock', {
  2816. get: () => false,
  2817. set: () => null,
  2818. enumerable: true
  2819. });
  2820. let _$ = {};
  2821. let _$_map = new WeakMap();
  2822. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2823. let _val_gOPD = _gOPD.value;
  2824. _gOPD.value = function(...args) {
  2825. let _res = _val_gOPD.apply(this, args);
  2826. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2827. delete _res.get;
  2828. delete _res.set;
  2829. _res.value = win[args[1]];
  2830. }
  2831. return _res;
  2832. };
  2833. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2834. let getJQWrap = (n) => {
  2835. let name = n;
  2836. return {
  2837. enumerable: true,
  2838. get: () => _$[name],
  2839. set: x => {
  2840. if (_$_map.has(x)) {
  2841. _$[name] = _$_map.get(x);
  2842. return true;
  2843. }
  2844. if (x === _$.$ || x === _$.jQuery) {
  2845. _$[name] = x;
  2846. return true;
  2847. }
  2848. _$[name] = new Proxy(x, {
  2849. apply: (t, o, args) => {
  2850. let _res = t.apply(o, args);
  2851. if (_$_map.has(_res.is))
  2852. _res.is = _$_map.get(_res.is);
  2853. else {
  2854. let _is = _res.is;
  2855. _res.is = function(...args) {
  2856. if (args[0] === ':hidden')
  2857. return false;
  2858. return _is.apply(this, args);
  2859. };
  2860. _$_map.set(_is, _res.is);
  2861. }
  2862. return _res;
  2863. }
  2864. });
  2865. _$_map.set(x, _$[name]);
  2866. return true;
  2867. }
  2868. };
  2869. };
  2870. Object.defineProperty(win, '$', getJQWrap('$'));
  2871. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2872. let _dP = Object.defineProperty;
  2873. Object.defineProperty = function(...args) {
  2874. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2875. return void 0;
  2876. return _dP.apply(this, args);
  2877. };
  2878. })
  2879. };
  2880.  
  2881. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2882. let nt = new nullTools();
  2883. /*jslint evil: true */ // yes, evil, I know
  2884. let _write = _document.write.bind(_document);
  2885. /*jslint evil: false */
  2886. nt.define(_document, 'write', t => {
  2887. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2888. if (id && id[1])
  2889. return _write(`<div id="${id[1]}"></div>${t}`);
  2890. return _write('');
  2891. });
  2892. });
  2893.  
  2894. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  2895.  
  2896. scripts['ivi.ru'] = () => {
  2897. let _xhr_open = win.XMLHttpRequest.prototype.open;
  2898. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  2899. if (typeof url === 'string')
  2900. if (url.endsWith('/track'))
  2901. return;
  2902. return _xhr_open.call(this, method, url, ...args);
  2903. };
  2904. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  2905. let _responseText_get = _responseText.get;
  2906. _responseText.get = function() {
  2907. if (this.__responseText__)
  2908. return this.__responseText__;
  2909. let res = _responseText_get.apply(this, arguments);
  2910. let o;
  2911. try {
  2912. if (res)
  2913. o = JSON.parse(res);
  2914. } catch(ignore) {};
  2915. let changed = false;
  2916. if (o && o.result) {
  2917. if (o.result instanceof Array &&
  2918. 'adv_network_logo_url' in o.result[0]) {
  2919. o.result = [];
  2920. changed = true;
  2921. }
  2922. if (o.result.show_adv) {
  2923. o.result.show_adv = false;
  2924. changed = true;
  2925. }
  2926. }
  2927. if (changed) {
  2928. _console.log('changed response >>', o);
  2929. res = JSON.stringify(o);
  2930. }
  2931. this.__responseText__ = res;
  2932. return res;
  2933. };
  2934. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  2935. };
  2936.  
  2937. scripts['kinopoisk.ru'] = () => {
  2938. selectiveCookies('bltsr|cmtchd|crookie|kpunk');
  2939. // set no-branding body style and adjust other blocks on the page
  2940. let style = [
  2941. '.app__header.app__header_margin-bottom_brand, #top { margin-bottom: 20px !important }',
  2942. '.app__branding { display: none !important}'
  2943. ];
  2944. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  2945. style.push('html:not(#id), body:not(#id), .app-container { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2946. createStyle(style);
  2947. // catch branding and other things
  2948. let _KP = void 0;
  2949. Object.defineProperty(win, 'KP', {
  2950. get: () => _KP,
  2951. set: val => {
  2952. if (_KP === val)
  2953. return true;
  2954. _KP = new Proxy(val, {
  2955. set: (kp, name, val) => {
  2956. if (name === 'branding') {
  2957. kp[name] = new Proxy({ weborama: {} }, {
  2958. get: (kp, name) => name in kp ? kp[name] : '',
  2959. set: () => true
  2960. });
  2961. return true;
  2962. }
  2963. if (name === 'config')
  2964. val = new Proxy(val, {
  2965. set: (cfg, name, val) => {
  2966. if (name === 'anContextUrl')
  2967. return true;
  2968. if (name === 'adfoxEnabled' || name === 'hasBranding')
  2969. val = false;
  2970. if (name === 'adfoxVideoAdUrls')
  2971. val = {flash:{}, html:{}};
  2972. cfg[name] = val;
  2973. return true;
  2974. }
  2975. });
  2976. kp[name] = val;
  2977. return true;
  2978. }
  2979. });
  2980. _console.log('KP =', val);
  2981. }
  2982. });
  2983. // skip branding and some other junk
  2984. Object.defineProperty(win, 'advBlock', {
  2985. get: () => () => null,
  2986. set: () => true
  2987. });
  2988. // skip timeout check for blocked requests
  2989. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  2990. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2991. win.setTimeout = function(...args) {
  2992. if (args[1] === 100) {
  2993. let str = _toString(args[0]);
  2994. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  2995. return;
  2996. }
  2997. return _setTimeout(this, args);
  2998. };
  2999. };
  3000.  
  3001. scripts['kinozal-tv.appspot.com'] = {
  3002. other: ['a-dot-kinozal-tv.appspot.com'],
  3003. now: () => {
  3004. // They check if 'startsWith' in String.prototype
  3005. // and skip parts of ABP detector if it's not there
  3006. delete String.prototype.startsWith;
  3007. }
  3008. };
  3009.  
  3010. scripts['korrespondent.net'] = {
  3011. now: () => scriptLander(() => {
  3012. let nt = new nullTools();
  3013. nt.define(win, 'holder', function(id) {
  3014. let div = _document.getElementById(id);
  3015. if (!div)
  3016. return;
  3017. if (div.parentNode.classList.contains('col__sidebar')) {
  3018. div.parentNode.appendChild(div);
  3019. div.style.height = '300px';
  3020. }
  3021. });
  3022. }, nullTools),
  3023. dom: () => {
  3024. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3025. frame.parentNode.style.width = '1px';
  3026. }
  3027. };
  3028.  
  3029. scripts['liveinternet.ru'] = () => selectiveEval(evalPatternYandex);
  3030.  
  3031. scripts['mail.ru'] = {
  3032. other: ['ok.ru'],
  3033. now: () => {
  3034. selectiveCookies('act|s|t|p|testcookie');
  3035. scriptLander(() => {
  3036. let nt = new nullTools();
  3037. // Trick to prevent mail.ru from removing 3rd-party styles
  3038. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  3039. // Disable some of their counters
  3040. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  3041. if (location.hostname === 'e.mail.ru')
  3042. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  3043. else
  3044. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  3045.  
  3046. {
  3047. let missingCheck = {
  3048. get: (obj, name) => {
  3049. if (!(name in obj))
  3050. _console.warn(obj, 'missing:', name);
  3051. return obj[name];
  3052. }
  3053. };
  3054. let skipLog = (name, ret) => (...args) => (_console.log(`Skip ${name}(`, ...args, ')'), ret);
  3055. let createSkipLogObject = (baseName, list) => list.reduce(
  3056. (acc, cur) => (acc[cur] = skipLog(`${baseName}.${cur}`), acc),
  3057. {}
  3058. );
  3059. let redefiner = {
  3060. apply: (target, thisArg, args) => {
  3061. let res = void 0;
  3062. if (target._name === 'mrg-smokescreen/Welter')
  3063. res = {
  3064. isWelter: () => true,
  3065. wrap: skipLog(`${target._name}.wrap`)
  3066. };
  3067. if (target._name === 'mrg-smokescreen/StyleSheets')
  3068. res = createSkipLogObject(target._name, ['update', 'remove', 'insert', 'setup']);
  3069. if (target._name === 'mrg-honeypot/main')
  3070. res = { check: skipLog(`${target._name}.check`, false) };
  3071. if (target._name.startsWith('advert/rb/slot')) {
  3072. res = createSkipLogObject(target._name, ['get', 'getHTML', 'createBlock', 'onRedirect']);
  3073. res.slot = '0';
  3074. }
  3075. if (target._name.startsWith('OK/banners/'))
  3076. res = createSkipLogObject(target._name, ['activate', 'deactivate']);
  3077. if (target._name === 'mimic') {
  3078. res = createSkipLogObject(target._name, ['insertDirect', 'setup']);
  3079. res.version = "%PACKAGE_VERSION%";
  3080. }
  3081. if (target._name === 'advert/adman/adman')
  3082. res = createSkipLogObject(target._name, ['refresh', 'getBlock', 'init']);
  3083. if (res)
  3084. res = new Proxy(res, missingCheck);
  3085. else
  3086. res = target.apply(thisArg, args);
  3087. if (target._name === 'mrg-smokescreen/Utils')
  3088. res.extend = function(...args) {
  3089. let res = {
  3090. enable: false,
  3091. match: [],
  3092. links: []
  3093. };
  3094. _console.log(`${target._name}.extend(`, ...args, ') >>', res );
  3095. return res;
  3096. };
  3097. if (target._name === 'advert/RB') {
  3098. res.getSlots = () => [];
  3099. res.load._name = target._name + '.load';
  3100. res.load = new Proxy(res.load, redefiner);
  3101. }
  3102. _console.log(target._name, '(',...args,') >>', res);
  3103. return res;
  3104. }
  3105. };
  3106.  
  3107. let wrapAdFuncs = {
  3108. apply: (target, thisArg, args) => {
  3109. let module = args[0];
  3110. if (typeof module === 'string')
  3111. if (module.startsWith('mrg-smoke') ||
  3112. module.startsWith('mrg-context') ||
  3113. module.startsWith('mrg-honeypot') ||
  3114. module.startsWith('advert') ||
  3115. module.startsWith('mimic') ||
  3116. module.startsWith('OK/banner') ||
  3117. module === 'OK/Smokescreen') {
  3118. let fun = args[args.length-1];
  3119. fun._name = module;
  3120. args[args.length-1] = new Proxy(fun, redefiner);
  3121. }// else
  3122. // _console.log('Define:', args[0]);
  3123. return target.apply(thisArg, args);
  3124. }
  3125. };
  3126. let wrapDefine = def => {
  3127. if (!def)
  3128. return;
  3129. _console.log('define =', def);
  3130. def = new Proxy(def, wrapAdFuncs);
  3131. def._name = 'define';
  3132. return def;
  3133. };
  3134. let _define = wrapDefine(win.define);
  3135. Object.defineProperty(win, 'define', {
  3136. get: () => _define,
  3137. set: x => {
  3138. if (_define === x)
  3139. return true;
  3140. _define = wrapDefine(x);
  3141. return true;
  3142. }
  3143. });
  3144. }
  3145.  
  3146. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3147. let logger = {
  3148. apply: (target, thisArg, args) => {
  3149. let res = target.apply(thisArg, args);
  3150. _console.log(`${target._name}(`, ...args, `) >>`, res);
  3151. return res;
  3152. }
  3153. };
  3154.  
  3155. let _locator;
  3156. function wrapLocator(locator) {
  3157. if ('setup' in locator) {
  3158. let _setup = locator.setup;
  3159. locator.setup = function(o) {
  3160. if ('enable' in o) {
  3161. o.enable = false;
  3162. _console.log('Disable mimic mode.');
  3163. }
  3164. if ('links' in o) {
  3165. o.links = [];
  3166. _console.log('Call with empty list of sheets.');
  3167. }
  3168. return _setup.call(this, o);
  3169. };
  3170. locator.insertSheet = () => false;
  3171. locator.wrap = () => false;
  3172. }
  3173. try {
  3174. let names = [];
  3175. for (let name in locator)
  3176. if (locator[name] instanceof Function && name !== 'transform') {
  3177. locator[name]._name = "locator." + name;
  3178. locator[name] = new Proxy(locator[name], logger);
  3179. names.push(name);
  3180. }
  3181. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3182. } catch(e) {
  3183. _console.log(e);
  3184. }
  3185. _locator = locator;
  3186. }
  3187.  
  3188. function defineLocator(root) {
  3189. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3190. if (!loc_desc || loc_desc.set !== wrapLocator)
  3191. try {
  3192. Object.defineProperty(root, 'locator', {
  3193. set: wrapLocator,
  3194. get: () => _locator
  3195. });
  3196. } catch (err) {
  3197. _console.log('Unable to redefine "locator" object!!!', err);
  3198. }
  3199. }
  3200.  
  3201. let _honeyPot;
  3202. function defineDetector(mr) {
  3203. let __ = mr._ || {};
  3204. let setHoneyPot = o => {
  3205. if (!o || o === _honeyPot) return;
  3206. _console.log('[honeyPot]', o);
  3207. _honeyPot = function() {
  3208. this.check = new Proxy(() => {
  3209. __.STUCK_IN_POT = false;
  3210. return false;
  3211. }, logger);
  3212. this.check._name = 'honeyPot.check';
  3213. this.destroy = () => null;
  3214. };
  3215. };
  3216. if ('honeyPot' in mr)
  3217. setHoneyPot(mr.honeyPot);
  3218. else
  3219. Object.defineProperty(mr, 'honeyPot', {
  3220. get: () => _honeyPot,
  3221. set: setHoneyPot
  3222. });
  3223.  
  3224. __ = new Proxy(__, {
  3225. get: (t, p) => t[p],
  3226. set: (t, p, v) => {
  3227. _console.log(`mr._.${p} =`, v);
  3228. t[p] = v;
  3229. return true;
  3230. }
  3231. });
  3232. mr._ = __;
  3233. }
  3234.  
  3235. function defineAdd(mr) {
  3236. let _add;
  3237. let addWrapper = {
  3238. apply: (tgt, that, args) => {
  3239. let module = args[0];
  3240. if (typeof module === 'string' && module.startsWith('ad')) {
  3241. _console.log('Skip module:', module);
  3242. return;
  3243. }
  3244. if (typeof module === 'object' && module.name.startsWith('ad'))
  3245. _console.log('Loaded module:', module);
  3246. return logger.apply(tgt, that, args);
  3247. }
  3248. };
  3249. let setMrAdd = v => {
  3250. if (!v) return;
  3251. v._name = 'mr.add';
  3252. v = new Proxy(v, addWrapper);
  3253. _add = v;
  3254. };
  3255. if ('add' in mr)
  3256. setMrAdd(mr.add);
  3257. Object.defineProperty(mr, 'add', {
  3258. get: () => _add,
  3259. set: setMrAdd
  3260. });
  3261.  
  3262. }
  3263.  
  3264. let _mr_wrapper = vl => {
  3265. defineLocator(vl.mimic ? vl.mimic : vl);
  3266. defineDetector(vl);
  3267. defineAdd(vl);
  3268. return vl;
  3269. };
  3270. if ('mr' in win) {
  3271. _console.log('Found existing "mr" object.');
  3272. win.mr = _mr_wrapper(win.mr);
  3273. } else {
  3274. let _mr = void 0;
  3275. Object.defineProperty(win, 'mr', {
  3276. get: () => _mr,
  3277. set: vl => { _mr = _mr_wrapper(vl) },
  3278. configurable: true
  3279. });
  3280. let _defineProperty = Function.prototype.apply.bind(Object.defineProperty);
  3281. Object.defineProperty = function defineProperty(o, name, conf) {
  3282. if (name === 'mr' && o instanceof Window) {
  3283. _console.warn('Object.defineProperty(', ...arguments, ')');
  3284. conf.set(_mr_wrapper(conf.get()));
  3285. }
  3286. if ((name === 'honeyPot' || name === 'add') && _mr === o && conf.set)
  3287. return;
  3288. return _defineProperty(this, arguments);
  3289. };
  3290. }
  3291.  
  3292. // smokyTools wrapper for news.mail.ru
  3293. nt.define(win, 'smokyTools', nt.proxy({
  3294. getDict: nt.func(nt.proxy({}, 'smokyTools.getDict', null), 'smokyTools.getDict'),
  3295. CSS: nt.func(nt.proxy({}, 'smokyTools.CSS', null), 'smokyTools.CSS')
  3296. }, 'smokyTools', null));
  3297. nt.define(win, 'smoky', nt.func(null, 'smoky'));
  3298. nt.define(win, 'smokySingleElement', nt.func(null, 'smokySingleElement'));
  3299. nt.define(win, 'smokyByClass', nt.func(null, 'smokyByClass'));
  3300. }, nullTools);
  3301. }
  3302. };
  3303.  
  3304. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3305. let _rmpGlobals = void 0;
  3306. Object.defineProperty(win, 'rmpGlobals', {
  3307. get: () => _rmpGlobals,
  3308. set: x => {
  3309. if (x === _rmpGlobals)
  3310. return true;
  3311. _rmpGlobals = new Proxy(x, {
  3312. get: (obj, name) => {
  3313. if (name === 'adBlockerDetected')
  3314. return false;
  3315. return obj[name];
  3316. },
  3317. set: (obj, name, val) => {
  3318. if (name === 'adBlockerDetected')
  3319. _console.warn('rmpGlobals.adBlockerDetected =', val)
  3320. else
  3321. obj[name] = val;
  3322. return true;
  3323. }
  3324. });
  3325. }
  3326. });
  3327. });
  3328.  
  3329. scripts['megogo.net'] = {
  3330. now: () => {
  3331. let nt = new nullTools();
  3332. nt.define(win, 'adBlock', false);
  3333. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3334. }
  3335. };
  3336.  
  3337. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3338.  
  3339. scripts['newdeaf-online.net'] = {
  3340. dom: () => {
  3341. let adNodes = _document.querySelectorAll('.ads');
  3342. if (!adNodes)
  3343. return;
  3344. let getter = x => {
  3345. let val = x;
  3346. return () => (_console.warn('read .ads', name, val), val);
  3347. };
  3348. let setter = x => _console.warn('skip write .ads', name, x);
  3349. for (let adNode of adNodes)
  3350. for (let name of ['innerHTML'])
  3351. Object.defineProperty(adNode, name, {
  3352. get: getter(ads[name]),
  3353. set: setter
  3354. });
  3355. }
  3356. };
  3357.  
  3358. scripts['overclockers.ru'] = {
  3359. dom: () => scriptLander(() => {
  3360. let killed = () => _console.warn('Anti-Adblock killed.');
  3361. if ('$' in win)
  3362. win.$ = new Proxy($, {
  3363. apply: (tgt, that, args) => {
  3364. let res = tgt.apply(that, args);
  3365. if (res[0] && res[0] === _document.body) {
  3366. res.html = killed;
  3367. res.empty = killed;
  3368. }
  3369. return res;
  3370. }
  3371. });
  3372. })
  3373. };
  3374. scripts['forums.overclockers.ru'] = {
  3375. now: () => {
  3376. createStyle('.needblock {position: fixed; left: -10000px}');
  3377. Object.defineProperty(win, 'adblck', {
  3378. get: () => 'no',
  3379. set: () => undefined,
  3380. enumerable: true
  3381. });
  3382. }
  3383. };
  3384.  
  3385. scripts['pb.wtf'] = {
  3386. other: ['piratbit.org', 'piratbit.ru'],
  3387. dom: () => {
  3388. // line above topic content and images in the slider in the header
  3389. let remove = node => (_console.log('removed', node), node.parentNode.removeChild(node));
  3390. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3391. if (location.hostname === el.hostname &&
  3392. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3393. remove(el.closest('div, tr'));
  3394. continue;
  3395. }
  3396. // ads in the topic header in case filter above wasn't enough
  3397. let parent = el.closest('tr');
  3398. if (parent) {
  3399. let span = (parent.querySelector('span') || {}).textContent;
  3400. span && span.startsWith('YO!') && remove(parent);
  3401. }
  3402. }
  3403. // casino ad button in random places
  3404. for (let el of _document.querySelectorAll('.btn-group')) {
  3405. el = el.parentNode;
  3406. if (el.tagName === 'CENTER')
  3407. remove(el.parentNode);
  3408. }
  3409. // ads in comments
  3410. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3411. if (el && el.parentNode.children[2] == el)
  3412. remove(el);
  3413. }
  3414. };
  3415.  
  3416. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3417.  
  3418. scripts['peka2.tv'] = () => {
  3419. let bodyClass = 'body--branding';
  3420. let checkNode = node => {
  3421. for (let className of node.classList)
  3422. if (className.includes('banner') || className === bodyClass) {
  3423. _removeAttribute(node, 'style');
  3424. node.classList.remove(className);
  3425. for (let attr of Array.from(node.attributes))
  3426. if (attr.name.startsWith('advert'))
  3427. _removeAttribute(node, attr.name);
  3428. }
  3429. };
  3430. (new MutationObserver(ms => {
  3431. let m, node;
  3432. for (m of ms) for (node of m.addedNodes)
  3433. if (node instanceof HTMLElement)
  3434. checkNode(node);
  3435. })).observe(_de, {childList: true, subtree: true});
  3436. (new MutationObserver(ms => {
  3437. for (let m of ms)
  3438. checkNode(m.target);
  3439. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3440. };
  3441.  
  3442. scripts['qrz.ru'] = {
  3443. now: () => {
  3444. let nt = new nullTools();
  3445. nt.define(win, 'ab', false);
  3446. nt.define(win, 'tryMessage', nt.func(null));
  3447. }
  3448. };
  3449.  
  3450. scripts['razlozhi.ru'] = {
  3451. now: () => {
  3452. let nt = new nullTools();
  3453. nt.define(win, 'cadb', false);
  3454. for (let func of ['createShadowRoot', 'attachShadow'])
  3455. if (func in _Element)
  3456. _Element[func] = function(){
  3457. return this.cloneNode();
  3458. };
  3459. }
  3460. };
  3461.  
  3462. scripts['rbc.ru'] = {
  3463. other: ['autonews.ru', 'rbcplus.ru', 'sportrbc.ru'],
  3464. now: () => {
  3465. selectiveCookies('adb_on');
  3466. let _RA = void 0;
  3467. let setArgs = {
  3468. 'showBanners': true,
  3469. 'showAds': true,
  3470. 'banners.staticPath': '',
  3471. 'paywall.staticPath': '',
  3472. 'banners.dfp.config': [],
  3473. 'banners.dfp.pageTargeting': () => null,
  3474. };
  3475. Object.defineProperty(win, 'RA', {
  3476. get: () => _RA,
  3477. set: vl => {
  3478. _console.log('RA =', vl);
  3479. if ('repo' in vl) {
  3480. _console.log('RA.repo =', vl.repo);
  3481. vl.repo = new Proxy(vl.repo, {
  3482. set: (o, name, val) => {
  3483. if (name === 'banner') {
  3484. _console.log(`RA.repo.${name} =`, val);
  3485. val = new Proxy(val, {
  3486. get: (o, name) => {
  3487. let res = o[name];
  3488. if (typeof o[name] === 'function') {
  3489. res = () => null;
  3490. res.toString = o[name].toString.bind(o[name]);
  3491. }
  3492. if (name === 'isInited')
  3493. res = true;
  3494. _console.warn(`get RA.repo.banner.${name}`, res);
  3495. return res;
  3496. }
  3497. });
  3498. }
  3499. o[name] = val;
  3500. return true;
  3501. }
  3502. });
  3503. } else
  3504. _console.log('Unable to locate RA.repo');
  3505. _RA = new Proxy(vl, {
  3506. set: (o, name, val) => {
  3507. if (name === 'config') {
  3508. _console.log('RA.config =', val);
  3509. if ('set' in val) {
  3510. val.set = new Proxy(val.set, {
  3511. apply: (set, that, args) => {
  3512. let name = args[0];
  3513. if (name in setArgs)
  3514. args[1] = setArgs[name];
  3515. if (name in setArgs || name === 'checkad')
  3516. _console.log('RA.config.set(', ...args, ')');
  3517. return Reflect.apply(set, that, args);
  3518. }
  3519. });
  3520. val.set('showAds', true); // pretend ads already were shown
  3521. }
  3522. }
  3523. o[name] = val;
  3524. return true;
  3525. }
  3526. });
  3527. }
  3528. });
  3529. Object.defineProperty(win, 'bannersConfig', {
  3530. get: () => [], set: () => null
  3531. });
  3532. // pretend there is a paywall landing on screen already
  3533. let pwl = _document.createElement('div');
  3534. pwl.style.display = 'none';
  3535. pwl.className = 'js-paywall-landing';
  3536. _document.documentElement.appendChild(pwl);
  3537. // detect and skip execution of one of the ABP detectors
  3538. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3539. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3540. win.setTimeout = function setTimeout() {
  3541. if (typeof arguments[0] === 'function') {
  3542. let fts = _toString(arguments[0]);
  3543. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  3544. _console.log('Skipped setTimout(', fts, arguments[1], ')');
  3545. return;
  3546. }
  3547. }
  3548. return _setTimeout(this, arguments);
  3549. };
  3550. // hide banner placeholders
  3551. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  3552. },
  3553. dom: () => {
  3554. // hide sticky banner place at the top of the page
  3555. for (let itm of _document.querySelectorAll('.l-sticky'))
  3556. if (itm.querySelector('.banner__container__link'))
  3557. itm.style.display = 'none';
  3558. }
  3559. };
  3560.  
  3561. scripts['rp5.ru'] = {
  3562. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3563. now: () => {
  3564. Object.defineProperty(win, 'sContentBottom', {
  3565. get: () => '',
  3566. set: () => true
  3567. });
  3568. },
  3569. dom: () => {
  3570. let node = selectNodeByTextContent('Разместить текстовое объявление', { root: _de.querySelector('#content-wrapper'), shallow: true });
  3571. if (node)
  3572. node.style.display = 'none';
  3573. }
  3574. };
  3575.  
  3576. scripts['rutube.ru'] = () => scriptLander(() => {
  3577. let _parse = JSON.parse;
  3578. let _skip_enabled = false;
  3579. JSON.parse = (...args) => {
  3580. let res = _parse(...args),
  3581. log = false;
  3582. if (!res)
  3583. return res;
  3584. // parse player configuration
  3585. if ('appearance' in res || 'video_balancer' in res) {
  3586. log = true;
  3587. if (res.appearance) {
  3588. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3589. res.appearance.forbid_seek = false;
  3590. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3591. res.appearance.forbid_timeline_preview = false;
  3592. }
  3593. _skip_enabled = !!res.remove_unseekable_blocks;
  3594. //res.advert = [];
  3595. delete res.advert;
  3596. //for (let limit of res.limits)
  3597. // limit.limit = 0;
  3598. delete res.limits;
  3599. //res.yast = null;
  3600. //res.yast_live_online = null;
  3601. delete res.yast;
  3602. delete res.yast_live_online;
  3603. Object.defineProperty(res, 'stat', {
  3604. get: () => [],
  3605. set: () => true,
  3606. enumerable: true
  3607. });
  3608. }
  3609.  
  3610. // parse video configuration
  3611. if ('video_url' in res) {
  3612. log = true;
  3613. if (res.cuepoints && !_skip_enabled)
  3614. for (let point of res.cuepoints) {
  3615. point.is_pause = false;
  3616. point.show_navigation = true;
  3617. point.forbid_seek = false;
  3618. }
  3619. }
  3620.  
  3621. if (log)
  3622. _console.log('[rutube]', res);
  3623. return res;
  3624. };
  3625. });
  3626.  
  3627. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3628. let _addEventListener = _Document.addEventListener;
  3629. _document.addEventListener = function(event, callback) {
  3630. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3631. return;
  3632. return _addEventListener.apply(this, arguments);
  3633. };
  3634. });
  3635.  
  3636. scripts['smotret-anime.ru'] = () => scriptLander(() => {
  3637. deepWrapAPI(root => {
  3638. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3639. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3640. let stopper = e => _pause(e.target);
  3641. root.Audio = new Proxy(root.Audio, {
  3642. construct: (audio, args) => {
  3643. let res = new audio(...args);
  3644. _addEventListener(res, 'play', stopper, true);
  3645. return res;
  3646. }
  3647. });
  3648. _createElement = root.Document.prototype.createElement;
  3649. root.Document.prototype.createElement = function createElement() {
  3650. let res = _createElement.apply(this, arguments);
  3651. if (res instanceof HTMLAudioElement)
  3652. _addEventListener(res, 'play', stopper, true);
  3653. return res;
  3654. };
  3655. });
  3656. }, deepWrapAPI);
  3657.  
  3658. scripts['spaces.ru'] = () => {
  3659. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3660. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3661. };
  3662.  
  3663. scripts['spam-club.blogspot.co.uk'] = () => {
  3664. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  3665. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  3666. let wrapGetter = (getter) => {
  3667. let _getter = getter;
  3668. return function() {
  3669. let _size = _getter.apply(this, arguments);
  3670. return _size ? _size : 1;
  3671. };
  3672. };
  3673. _clientHeight.get = wrapGetter(_clientHeight.get);
  3674. _clientWidth.get = wrapGetter(_clientWidth.get);
  3675. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3676. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  3677. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3678. _set_onload = _onload.set;
  3679. _onload.set = function() {
  3680. if (this instanceof HTMLImageElement)
  3681. return true;
  3682. _set_onload.apply(this, arguments);
  3683. };
  3684. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3685. };
  3686.  
  3687. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3688.  
  3689. scripts['sports.ru'] = {
  3690. now: () => {
  3691. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3692. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3693. // extra functionality: shows/hides panel at the top depending on scroll direction
  3694. createStyle([
  3695. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3696. '.user-panel-up { top: -40px!important }'
  3697. ], {id: 'userPanelSlide'}, false);
  3698. },
  3699. dom: () => {
  3700. (function lookForPanel() {
  3701. let panel = _document.querySelector('.user-panel__fixed');
  3702. if (!panel)
  3703. setTimeout(lookForPanel, 100);
  3704. else
  3705. window.addEventListener(
  3706. 'wheel', function(e) {
  3707. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3708. panel.classList.add('user-panel-up');
  3709. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3710. panel.classList.remove('user-panel-up');
  3711. }, false
  3712. );
  3713. })();
  3714. }
  3715. };
  3716.  
  3717. scripts['stealthz.ru'] = {
  3718. dom: () => {
  3719. // skip timeout
  3720. let $ = _document.querySelector.bind(_document);
  3721. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3722. if (!timer_1 || !timer_2)
  3723. return;
  3724. timer_1.style.display = 'none';
  3725. timer_2.style.display = 'block';
  3726. }
  3727. };
  3728.  
  3729. scripts['xittv.net'] = () => scriptLander(() => {
  3730. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  3731. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  3732. let _jwplayer = void 0;
  3733. Object.defineProperty(win, 'jwplayer', {
  3734. get: () => _jwplayer,
  3735. set: x => {
  3736. _jwplayer = new Proxy(x, {
  3737. apply: (fun, that, args) => {
  3738. let res = fun.apply(that, args);
  3739. res = new Proxy(res, {
  3740. get: (obj, name) => {
  3741. if (logNames.includes(name) && obj[name] instanceof Function)
  3742. return new Proxy(obj[name], {
  3743. apply: (fun, that, args) => {
  3744. if (name === 'setup') {
  3745. let o = args[0];
  3746. if (o)
  3747. delete o.advertising;
  3748. }
  3749. if (name === 'on' || name === 'trigger') {
  3750. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  3751. if (events.length === 1 && skipEvents.includes(events[0]))
  3752. return res;
  3753. if (events.length > 1) {
  3754. let names = [];
  3755. for (let event of events)
  3756. if (!skipEvents.includes(event))
  3757. names.push(event);
  3758. if (names.length > 0)
  3759. args[0] = names.join(" ");
  3760. else
  3761. return res;
  3762. }
  3763. }
  3764. let subres = fun.apply(that, args);
  3765. _console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  3766. return subres;
  3767. }
  3768. });
  3769. return obj[name];
  3770. }
  3771. });
  3772. return res;
  3773. }
  3774. });
  3775. _console.log('jwplayer =', x);
  3776. }
  3777. });
  3778. });
  3779.  
  3780. scripts['yap.ru'] = {
  3781. other: ['yaplakal.com'],
  3782. now: () => {
  3783. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3784. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3785. }
  3786. };
  3787.  
  3788. scripts['rambler.ru'] = {
  3789. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  3790. now: () => {
  3791. selectiveCookies('detect_count');
  3792. scriptLander(() => {
  3793. // Prevent autoplay
  3794. if (!('EaglePlayer' in win)) {
  3795. let _EaglePlayer = void 0;
  3796. Object.defineProperty(win, 'EaglePlayer', {
  3797. enumerable: true,
  3798. get: () => _EaglePlayer,
  3799. set: x => {
  3800. if (x === _EaglePlayer)
  3801. return true;
  3802. _EaglePlayer = new Proxy(x, {
  3803. construct: (targ, args) => {
  3804. let player = new targ(...args);
  3805. if (!player.options) {
  3806. _console.log('EaglePlayer: no options', EaglePlayer);
  3807. return player;
  3808. }
  3809. Object.defineProperty(player.options, 'autoplay', {
  3810. get: () => false,
  3811. set: () => true
  3812. });
  3813. Object.defineProperty(player.options, 'scroll', {
  3814. get: () => false,
  3815. set: () => true
  3816. });
  3817. return player;
  3818. }
  3819. });
  3820. }
  3821. });
  3822. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3823. let isAutoplay = /^autoplay$/i;
  3824. _Element.setAttribute = function setAttribute(name) {
  3825. if (!this._stopped && isAutoplay.test(name)) {
  3826. _console.log('Prevented assigning autoplay attribute.');
  3827. return null;
  3828. }
  3829. return _setAttribute(this, arguments);
  3830. };
  3831. } else {
  3832. _console.log('EaglePlayer function already exists.');
  3833. if (inIFrame) {
  3834. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3835. let isAutoplay = /^autoplay$/i;
  3836. _Element.setAttribute = function setAttribute(name) {
  3837. if (!this._stopped && isAutoplay.test(name)) {
  3838. _console.log('Prevented assigning autoplay attribute.');
  3839. this._stopped = true;
  3840. this.play = () => {
  3841. _console.log('Prevented attempt to force-start playback.');
  3842. delete this.play;
  3843. };
  3844. return null;
  3845. }
  3846. return _setAttribute(this, arguments);
  3847. };
  3848. }
  3849. }
  3850. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3851. return;
  3852. let nt = new nullTools();
  3853. // Adblock Detector
  3854. let _hidden = void 0;
  3855. Object.defineProperty(win, 'QW50aS1BZEJsb2Nr', {
  3856. set: vl => {
  3857. for (let name in vl) delete vl[name];
  3858. nt.define(vl, 'Detector', nt.proxy({
  3859. getBlockingStatus: () => new Promise(),
  3860. blockingDetectors: [],
  3861. baitURLPrefix: '',
  3862. commonRules: []
  3863. }));
  3864. nt.define(vl, 'isAdBlockFlag', '');
  3865. nt.define(vl, 'ruid', '');
  3866. nt.define(vl, 'user', nt.proxy({
  3867. getOrSetUid: () => null
  3868. }));
  3869. _console.log('Found Adblock Detector.');
  3870. _hidden = vl;
  3871. },
  3872. get: () => _hidden
  3873. });
  3874. // prevent ads from loading
  3875. let blockObfuscated = false;
  3876. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  3877. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3878. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3879. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3880. let _cssText_get = _cssText.get;
  3881. _cssText.configurable = false;
  3882. _cssText.get = function() {
  3883. let cssText = _cssText_get.call(this);
  3884. if (cssText.includes('content:')) {
  3885. _console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3886. blockObfuscated = true;
  3887. return null;
  3888. }
  3889. return cssText;
  3890. };
  3891. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3892. let _setTimeout = win.setTimeout;
  3893. win.setTimeout = function(f) {
  3894. if (blockObfuscated && obfuscation.test(_toString(f))) {
  3895. _console.warn('Stopped setTimeout for:', _toString(f).slice(0,100), '\u2026');
  3896. return null;
  3897. };
  3898. return _setTimeout.apply(this, arguments);
  3899. };
  3900. // fake global Adf object
  3901. let Adf_banner = {};
  3902. [
  3903. 'reloadssp', 'sspScroll',
  3904. 'sspRich', 'ssp'
  3905. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3906. nt.define(win, 'Adf', nt.proxy({
  3907. banner: nt.proxy(Adf_banner)
  3908. }));
  3909. // extra script to remove partner news on gazeta.ru
  3910. if (!location.hostname.includes('gazeta.ru'))
  3911. return;
  3912. (new MutationObserver(
  3913. (ms) => {
  3914. let m, node, header;
  3915. for (m of ms) for (node of m.addedNodes)
  3916. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3917. header = node.querySelector('.sausage-header');
  3918. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3919. node.style.display = 'none';
  3920. }
  3921. }
  3922. )).observe(_document.documentElement, { childList:true, subtree: true });
  3923. }, `let inIFrame = ${inIFrame}`, nullTools)
  3924. }
  3925. };
  3926.  
  3927. scripts['reactor.cc'] = {
  3928. other: ['joyreactor.cc', 'pornreactor.cc'],
  3929. now: () => {
  3930. selectiveEval();
  3931. scriptLander(() => {
  3932. let nt = new nullTools();
  3933. win.open = function(){
  3934. throw new Error('Redirect prevention.');
  3935. };
  3936. nt.define(win, 'Worker', function(){});
  3937. nt.define(win, 'JRCH', win.CoinHive);
  3938. }, nullTools);
  3939. },
  3940. click: function(e) {
  3941. let node = e.target;
  3942. if (node.nodeType === _Node.ELEMENT_NODE &&
  3943. node.style.position === 'absolute' &&
  3944. node.style.zIndex > 0)
  3945. node.parentNode.removeChild(node);
  3946. },
  3947. dom: function() {
  3948. let tid = void 0;
  3949. function probe() {
  3950. let node = selectNodeByTextContent('блокировщик рекламы');
  3951. if (!node) return;
  3952. while (node.parentNode.offsetHeight < 750 && node !== _document.body)
  3953. node = node.parentNode;
  3954. _setAttribute(node, 'style', 'background:none!important');
  3955. // stop observer
  3956. if (!tid) tid = setTimeout(() => this.disconnect(), 1000);
  3957. }
  3958. (new MutationObserver(probe))
  3959. .observe(_document, { childList:true, subtree:true });
  3960. }
  3961. };
  3962.  
  3963. scripts['auto.ru'] = () => {
  3964. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3965. let userAdsListAds = (
  3966. '.listing-list > .listing-item,'+
  3967. '.listing-item_type_fixed.listing-item'
  3968. );
  3969. let catalogAds = (
  3970. 'div[class*="layout_catalog-inline"],'+
  3971. 'div[class$="layout_horizontal"]'
  3972. );
  3973. let otherAds = (
  3974. '.advt_auto,'+
  3975. '.sidebar-block,'+
  3976. '.pager-listing + div[class],'+
  3977. '.card > div[class][style],'+
  3978. '.sidebar > div[class],'+
  3979. '.main-page__section + div[class],'+
  3980. '.listing > tbody'
  3981. );
  3982. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3983. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3984. gardener(otherAds, words);
  3985. };
  3986.  
  3987. scripts['rsload.net'] = {
  3988. load: () => {
  3989. let dis = _document.querySelector('label[class*="cb-disable"]');
  3990. if (dis)
  3991. dis.click();
  3992. },
  3993. click: e => {
  3994. let t = e.target;
  3995. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3996. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3997. }
  3998. };
  3999.  
  4000. let domain;
  4001. // add alternative domain names if present and wrap functions into objects
  4002. for (let name in scripts) {
  4003. if (scripts[name] instanceof Function)
  4004. scripts[name] = { now: scripts[name] };
  4005. for (domain of (scripts[name].other||[])) {
  4006. if (domain in scripts)
  4007. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  4008. scripts[domain] = scripts[name];
  4009. }
  4010. delete scripts[name].other;
  4011. }
  4012. // look for current domain in the list and run appropriate code
  4013. domain = _document.domain;
  4014. while (domain.includes('.')) {
  4015. if (domain in scripts) for (let when in scripts[domain])
  4016. switch(when) {
  4017. case 'now':
  4018. scripts[domain][when]();
  4019. break;
  4020. case 'dom':
  4021. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  4022. break;
  4023. default:
  4024. _document.addEventListener (when, scripts[domain][when], false);
  4025. }
  4026. domain = domain.slice(domain.indexOf('.') + 1);
  4027. }
  4028.  
  4029. // Batch script lander
  4030. if (!skipLander)
  4031. landScript(batchLand, batchPrepend);
  4032.  
  4033. { // JS Fixes Tools Menu
  4034. let openOptions = function() {
  4035. let ovl = _createElement('div'),
  4036. inner = _createElement('div');
  4037. ovl.style = (
  4038. 'position: fixed;'+
  4039. 'top:0; left:0;'+
  4040. 'bottom: 0; right: 0;'+
  4041. 'background: rgba(0,0,0,0.85);'+
  4042. 'z-index: 2147483647;'+
  4043. 'padding: 5em'
  4044. );
  4045. inner.style = (
  4046. 'background: whitesmoke;'+
  4047. 'font-size: 10pt;'+
  4048. 'color: black;'+
  4049. 'padding: 1em'
  4050. );
  4051. inner.textContent = 'JS Fixes Tools';
  4052. inner.appendChild(_createElement('br'));
  4053. inner.appendChild(_createElement('br'));
  4054. ovl.addEventListener(
  4055. 'click', function(e) {
  4056. if (e.target === ovl) {
  4057. ovl.parentNode.removeChild(ovl);
  4058. e.preventDefault();
  4059. }
  4060. e.stopPropagation();
  4061. }, false
  4062. );
  4063.  
  4064. let sObjBtn = _createElement('button');
  4065. sObjBtn.onclick = getStrangeObjectsList;
  4066. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  4067. inner.appendChild(_createElement('br'));
  4068. inner.appendChild(sObjBtn);
  4069.  
  4070. _document.body.appendChild(ovl);
  4071. ovl.appendChild(inner);
  4072. };
  4073.  
  4074. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  4075. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  4076. _document.addEventListener(
  4077. 'keydown', function(e) {
  4078. if ((e.code === opKey[opPos] || e.location) &&
  4079. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  4080. opPos += e.location ? 0 : 1;
  4081. e.stopPropagation();
  4082. e.preventDefault();
  4083. } else
  4084. opPos = 0;
  4085. if (opPos === opKey.length) {
  4086. opPos = 0;
  4087. openOptions();
  4088. }
  4089. }, false
  4090. );
  4091. }
  4092. })();