RU AdList JS Fixes

try to take over the world!

当前为 2020-05-23 提交的版本,查看 最新版本

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