RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址