RU AdList JS Fixes

try to take over the world!

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

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