RU AdList JS Fixes

try to take over the world!

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

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