RU AdList JS Fixes

try to take over the world!

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

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