RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址