RU AdList JS Fixes

try to take over the world!

目前為 2020-03-05 提交的版本,檢視 最新版本

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