RU AdList JS Fixes

try to take over the world!

当前为 2020-01-17 提交的版本,查看 最新版本

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