RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

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