RU AdList JS Fixes

try to take over the world!

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

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