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