RU AdList JS Fixes

try to take over the world!

目前為 2020-06-20 提交的版本,檢視 最新版本

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