RU AdList JS Fixes

try to take over the world!

当前为 2020-09-11 提交的版本,查看 最新版本

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