RU AdList JS Fixes

try to take over the world!

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

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