RU AdList JS Fixes

try to take over the world!

当前为 2020-07-17 提交的版本,查看 最新版本

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