RU AdList JS Fixes

try to take over the world!

目前為 2020-01-22 提交的版本,檢視 最新版本

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