RU AdList JS Fixes

try to take over the world!

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

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