RU AdList JS Fixes

try to take over the world!

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

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