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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址