RU AdList JS Fixes

try to take over the world!

当前为 2020-06-22 提交的版本,查看 最新版本

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