Greasy Fork 支持简体中文。

RU AdList JS Fixes

try to take over the world!

目前為 2020-07-21 提交的版本,檢視 最新版本

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