RU AdList JS Fixes

try to take over the world!

当前为 2019-02-16 提交的版本,查看 最新版本

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