RU AdList JS Fixes

try to take over the world!

当前为 2020-01-15 提交的版本,查看 最新版本

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