RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

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