RU AdList JS Fixes

try to take over the world!

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

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