RU AdList JS Fixes

try to take over the world!

当前为 2020-05-08 提交的版本,查看 最新版本

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