RU AdList JS Fixes

try to take over the world!

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

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