RU AdList JS Fixes

try to take over the world!

当前为 2017-12-22 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20171222.0
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @match *://*/*
  8. // @exclude *://*.alfabank.ru/*
  9. // @exclude *://alfabank.ru/*
  10. // @exclude *://*.unicreditbanking.net/*
  11. // @exclude *://unicreditbanking.net/*
  12. // @grant unsafeWindow
  13. // @grant window.close
  14. // @grant GM_getValue
  15. // @grant GM_setValue
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. (function() {
  20. 'use strict';
  21. let win = (unsafeWindow || window),
  22. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  23. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  24. isChrome = !!window.chrome && !!window.chrome.webstore,
  25. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  26. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  27. isFirefox = typeof InstallTrigger !== 'undefined',
  28. inIFrame = (win.self !== win.top),
  29. _getAttribute = Element.prototype.getAttribute,
  30. _setAttribute = Element.prototype.setAttribute,
  31. _removeAttribute = Element.prototype.removeAttribute,
  32. _de = document.documentElement,
  33. _appendChild = Document.prototype.appendChild.bind(_de),
  34. _removeChild = Document.prototype.removeChild.bind(_de),
  35. _createElement = Document.prototype.createElement.bind(document);
  36.  
  37. if (isFirefox && // Exit on image pages in Fx
  38. document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  39. return;
  40.  
  41. // dTree 2.05 in some cases replaces Node object before my script kicks in :(
  42. if (!Node.prototype)
  43. {
  44. let ifr = _createElement('iframe');
  45. _appendChild(ifr);
  46. try {
  47. window.Node = ifr.contentWindow.Node;
  48. console.log('Node object restored. -_-');
  49. } catch(e) {
  50. console.log('Unable to restore Node object.', e);
  51. }
  52. _removeChild(ifr);
  53. }
  54.  
  55. // NodeList iterator polyfill (mostly for Safari)
  56. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  57. if (!NodeList.prototype[Symbol.iterator]) {
  58. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  59. }
  60.  
  61. (function initOpts() {
  62. let getGlobal, setGlobal, exit = false;
  63. try {
  64. getGlobal = GM_getValue;
  65. setGlobal = GM_setValue;
  66. } catch (ignore) {
  67. // exit if old GM API is not available
  68. // promise-based equivalents postpone code execution for too long
  69. exit = true;
  70. }
  71.  
  72. // Options
  73. let opts = {
  74. 'useWSIFunc': useWSI
  75. };
  76. if (exit) {
  77. for (let func in opts)
  78. opts[func]();
  79. return;
  80. }
  81.  
  82. {
  83. let optsCall = function(callback)
  84. {
  85. // Register event listener
  86. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  87. cb = callback.func.bind(callback.name);
  88. window.addEventListener(key, cb, false);
  89. // Generate and dispatch synthetic event
  90. let ev = document.createEvent("HTMLEvents");
  91. ev.initEvent(key, true, false);
  92. window.dispatchEvent(ev);
  93. // Remove listener
  94. window.removeEventListener(key, cb, false);
  95. };
  96.  
  97. let initOptsHandler = function()
  98. {
  99. opts[this] = getGlobal(this, true);
  100. if (opts[this])
  101. opts[this+'Func']();
  102. };
  103.  
  104. optsCall({
  105. func: initOptsHandler,
  106. name: 'useWSI'
  107. });
  108.  
  109. // show options page
  110. let openOptions = function()
  111. {
  112. let ovl = _createElement('div'),
  113. inner = _createElement('div');
  114. ovl.style = (
  115. 'position: fixed;'+
  116. 'top:0; left:0;'+
  117. 'bottom: 0; right: 0;'+
  118. 'background: rgba(0,0,0,0.85);'+
  119. 'z-index: 2147483647;'+
  120. 'padding: 5em'
  121. );
  122. inner.style = (
  123. 'background: whitesmoke;'+
  124. 'font-size: 10pt;'+
  125. 'color: black;'+
  126. 'padding: 1em'
  127. );
  128. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  129. inner.appendChild(_createElement('br'));
  130. inner.appendChild(_createElement('br'));
  131. ovl.addEventListener(
  132. 'click', function(e)
  133. {
  134. if (e.target === ovl) {
  135. ovl.parentNode.removeChild(ovl);
  136. e.preventDefault();
  137. }
  138. e.stopPropagation();
  139. }, false
  140. );
  141. // append checkbox with label function
  142. function addCheckbox(optName, optLabel)
  143. {
  144. let c = _createElement('input'),
  145. l = _createElement('label');
  146. c.type = 'checkbox';
  147. c.id = optName;
  148. optsCall({
  149. func: function()
  150. {
  151. c.checked = getGlobal(this);
  152. },
  153. name: optName
  154. });
  155. c.addEventListener(
  156. 'click', function(e)
  157. {
  158. optsCall({
  159. func:function(){
  160. setGlobal(this, e.target.checked);
  161. opts[this] = e.target.checked;
  162. },
  163. name:optName
  164. });
  165. }, true
  166. );
  167. l.textContent = optLabel;
  168. l.setAttribute('for', optName);
  169. inner.appendChild(c);
  170. inner.appendChild(l);
  171. inner.appendChild(_createElement('br'));
  172. }
  173. // append checkboxes
  174. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  175.  
  176. let sObjBtn = _createElement('button');
  177. sObjBtn.onclick = getStrangeObjectsList;
  178. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  179. inner.appendChild(_createElement('br'));
  180. inner.appendChild(sObjBtn);
  181.  
  182. document.body.appendChild(ovl);
  183. ovl.appendChild(inner);
  184. };
  185.  
  186. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  187. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  188. document.addEventListener(
  189. 'keydown', function(e)
  190. {
  191. if ((e.code === opKey[opPos] || e.location) &&
  192. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  193. {
  194. opPos += e.location ? 0 : 1;
  195. e.stopPropagation();
  196. e.preventDefault();
  197. } else {
  198. opPos = 0;
  199. }
  200. if (opPos === opKey.length)
  201. {
  202. opPos = 0;
  203. openOptions();
  204. }
  205. }, false
  206. );
  207. }
  208. })();
  209.  
  210. // Special wrapper script to run scripts designed to override standard DOM functions
  211. // In Firefox appends supplied script to a page to make it run in page context and let
  212. // page content access overridden functions. In other browsers just run it as-is.
  213. function scriptLander(func, ...prepend)
  214. {
  215. if (!isFirefox)
  216. {
  217. func();
  218. return;
  219. }
  220. let script = _createElement('script');
  221. script.textContent = `(function(){let win=window;${(
  222. (prepend.length > 0 ? prepend.join(';') : '')
  223. )};(${func})();})();`;
  224. _appendChild(script);
  225. _removeChild(script);
  226. }
  227.  
  228. function nullTools(opts) {
  229. // jshint validthis:true
  230. let nt = this;
  231. opts = opts || {};
  232. function log() { if (opts.log) console.log(...arguments); }
  233. function trace() { if (opts.log) console.warn(...arguments); }
  234.  
  235. nt.destroy = function(o, destroy)
  236. {
  237. if (!opts.destroy && !destroy && o instanceof Object)
  238. return;
  239. log('cleaning', o);
  240. try {
  241. for (let item in o)
  242. {
  243. if (item instanceof Object)
  244. nt.destroy(item);
  245. delete o[item];
  246. }
  247. } catch (e) {
  248. log('Error in object destructor', e);
  249. }
  250. };
  251.  
  252. nt.define = function(obj, prop, val, enumerable = true)
  253. {
  254. try {
  255. Object.defineProperty(
  256. obj, prop, {
  257. get: () => val,
  258. set: (v) => (v !== val ? (log(`set ${prop} of`, obj, 'to', v), nt.destroy(v)) : null, undefined),
  259. enumerable: enumerable
  260. }
  261. );
  262. } catch (err) {
  263. console.log(`Unable to redefine "${prop}" in `, obj, err);
  264. }
  265. };
  266. nt.proxy = function(obj)
  267. {
  268. return new Proxy(
  269. obj, {
  270. get: (t, p) => p in t ? t[p] : console.warn(`Missing ${p} in`, t),
  271. set: (t, p, v) => (v !== t[p] ? (log(`set ${p} of`, t, 'to', v), nt.destroy(v)) : null, true)
  272. }
  273. );
  274. };
  275. nt.func = (val, name = '') => () => (trace(`call func ${name}, return`, val, true), val);
  276. }
  277.  
  278. // Debug function, lists all unusual window properties
  279. function getStrangeObjectsList()
  280. {
  281. console.warn('Strangers list start');
  282. let ifr = document.createElement('iframe');
  283. ifr.onload = () => {
  284. for (let name in win)
  285. if (!(name in ifr.contentWindow))
  286. console.log(name);
  287. };
  288. document.documentElement.appendChild(ifr);
  289. document.documentElement.removeChild(ifr);
  290. console.warn('Strangers list end');
  291. }
  292.  
  293. // Fake objects of advertisement networks to break their workflow
  294. scriptLander(
  295. function()
  296. {
  297. let nt = new nullTools();
  298. // Popular adblock detector
  299. if (!('fuckAdBlock' in win))
  300. {
  301. let FuckAdBlock = function(options) {
  302. let self = this;
  303. self._options = {
  304. checkOnLoad: false,
  305. resetOnEnd: false,
  306. checking: false
  307. };
  308. self.setOption = function(opt, val)
  309. {
  310. if (val)
  311. self._options[opt] = val;
  312. else
  313. Object.assign(self._options, opt);
  314. };
  315. if (options)
  316. self.setOption(options);
  317.  
  318. self._var = { event: {} };
  319. self.clearEvent = function()
  320. {
  321. self._var.event.detected = [];
  322. self._var.event.notDetected = [];
  323. };
  324. self.clearEvent();
  325.  
  326. self.on = function(detected, fun)
  327. {
  328. self._var.event[detected?'detected':'notDetected'].push(fun);
  329. return self;
  330. };
  331. self.onDetected = function(cb)
  332. {
  333. return self.on(true, cb);
  334. };
  335. self.onNotDetected = function(cb)
  336. {
  337. return self.on(false, cb);
  338. };
  339. self.emitEvent = function()
  340. {
  341. for (let fun of self._var.event.notDetected)
  342. fun();
  343. if (self._options.resetOnEnd)
  344. self.clearEvent();
  345. return self;
  346. };
  347. self._creatBait = () => null;
  348. self._destroyBait = () => null;
  349. self._checkBait = function() {
  350. setTimeout((() => self.emitEvent()), 1);
  351. };
  352. self.check = function() {
  353. self._checkBait();
  354. return true;
  355. };
  356.  
  357. let callback = function()
  358. {
  359. if (self._options.checkOnLoad)
  360. setTimeout(self.check, 1);
  361. };
  362. window.addEventListener('load', callback, false);
  363. };
  364. nt.define(win, 'FuckAdBlock', FuckAdBlock);
  365. nt.define(win, 'fuckAdBlock', new FuckAdBlock({
  366. checkOnLoad: true,
  367. resetOnEnd: true
  368. }));
  369. }
  370.  
  371. // go.onclasrv.com pop-ups/tab-uners
  372. if (!('zfgloadedpopup' in win))
  373. nt.define(win, 'zfgloadedpopup', true);
  374.  
  375. // CoinHive miner stub. Continuous 100% CPU load can easily kill some CPU with overheat.
  376. if (!('CoinHive' in win))
  377. {
  378. if (location.hostname !== 'cnhv.co')
  379. {
  380. // CoinHive stub for cases when it doesn't affect site functionality
  381. let CoinHiveConstructor = function()
  382. {
  383. console.warn('Fake CoinHive miner created.');
  384. this.setThrottle = nt.func(null);
  385. this.start = nt.func(null);
  386. this.on = nt.func(null);
  387. this.getTotalHashes = nt.func(0);
  388. };
  389. let CoinHiveStub = nt.proxy({
  390. Anonymous: CoinHiveConstructor,
  391. User: CoinHiveConstructor,
  392. Token: CoinHiveConstructor,
  393. JobThread: nt.func(null),
  394. IF_EXCLUSIVE_TAB: false
  395. });
  396. nt.define(win, 'CoinHive', CoinHiveStub);
  397. } else {
  398. // CoinHive wrapper to fool sites which expect it to actually work and return results
  399. let CoinHiveObject;
  400. let fishnet = {
  401. apply: (target, thisArg, args) => {
  402. console.log(`miner.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  403. return target.apply(thisArg, args);
  404. }
  405. };
  406. Object.defineProperty(win, 'CoinHive', {
  407. set: function(obj)
  408. {
  409. if ('Token' in obj)
  410. {
  411. console.log('[CoinHive] Token wrapper applied.');
  412. let _Token = obj.Token.bind(obj);
  413. obj.Token = function(siteKey, goal, params)
  414. {
  415. let _goal = goal;
  416. if (goal > 256)
  417. goal = 256;
  418. console.log(`[CoinHive] Original goal: ${_goal}, new smaller goal ${goal}.`);
  419. console.log(`With smaller goals server may return 'invalid_goal' error and stop working.`);
  420. let miner = _Token(siteKey, goal, params);
  421. miner.setThrottle(0.99);
  422. miner.setThrottle = () => null;
  423. let _start = miner.start.bind(miner);
  424. miner.start = function() {
  425. let res = _start(CoinHive.FORCE_EXCLUSIVE_TAB);
  426. return res;
  427. };
  428. let _getTotalHashes = miner.getTotalHashes;
  429. miner.getTotalHashes = function()
  430. {
  431. return Math.trunc(_getTotalHashes.call(this) / goal * _goal);
  432. };
  433. let __emit = miner._emit;
  434. miner._emit = function(state, props)
  435. {
  436. let _self = this;
  437. console.log('[CoinHive] state:', state, props);
  438. if (state === 'job')
  439. setTimeout(() => {
  440. _self.stop();
  441. _self._emit('accepted', { hashes: goal });
  442. }, 1000);
  443. return __emit.apply(_self, arguments);
  444. };
  445. let _on = miner.on.bind(miner);
  446. miner.on = function(type, callback)
  447. {
  448. if (type === 'accepted')
  449. {
  450. console.log('[CoinHive] "accepted" callback wrapper applied.');
  451. let _callback = callback;
  452. callback = function(params)
  453. {
  454. console.log('[CoinHive] "accepted" callback is called, imitating original goal being reached.');
  455. params.hashes = _goal;
  456. return _callback.apply(this, arguments);
  457. };
  458. miner.stop();
  459. }
  460. return _on(type, callback);
  461. };
  462. return miner;
  463. };
  464. }
  465. CoinHiveObject = obj;
  466. },
  467. get: () => CoinHiveObject
  468. });
  469. }
  470. }
  471.  
  472. // Yandex API (ADBTools, Metrika)
  473. let hostname = location.hostname;
  474. if (hostname.startsWith('google.') || hostname.includes('.google.') ||
  475. // Google likes to define odd global variables like Ya
  476. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  477. /^\/((yand)?search|images)/i.test(location.pathname) &&
  478. !hostname.startsWith('news.')) ||
  479. // Also, Yandex uses their Ya object for a lot of things on their pages and
  480. // wrapping it may cause problems. It's better to skip it in some cases.
  481. hostname.endsWith('github.io') || hostname.endsWith('grimtools.com'))
  482. return;
  483.  
  484. let YaProps = new Set();
  485. function onAdvManager (Ya, rootProp, obj)
  486. {
  487. return new Proxy(obj, {
  488. set: (tgt, prop, val) => {
  489. if (prop === 'AdvManager')
  490. {
  491. console.log(`Ya.${rootProp} = Ya.Context`);
  492. nt.define(Ya, rootProp, Ya.Context);
  493. YaProps.add(rootProp);
  494. }
  495. tgt[prop] = val;
  496. return true;
  497. },
  498. get: (tgt, prop) => tgt[prop]
  499. });
  500. }
  501. let Ya = new Proxy({}, {
  502. set: function(tgt, prop, val)
  503. {
  504. if (val === tgt[prop])
  505. return true;
  506. if (!isNaN(prop))
  507. {
  508. nt.define(Ya, prop, nt.func(null));
  509. YaProps.add(prop);
  510. }
  511. if (YaProps.has(prop))
  512. {
  513. console.log(`Ya.${prop} \u2260`, val);
  514. return true;
  515. }
  516. if (val instanceof Object && prop !== '__inline_params__')
  517. val = onAdvManager(Ya, prop, val);
  518. tgt[prop] = val;
  519. console.log(`Ya.${prop} =`, val);
  520. return true;
  521. },
  522. get: (tgt, prop) => tgt[prop]
  523. });
  524. let callWithParams = function(f)
  525. {
  526. f.call(this, Ya.__inline_params__ || {});
  527. Ya.__inline_params__ = null;
  528. };
  529. nt.define(Ya, 'callWithParams', callWithParams);
  530. nt.define(Ya, 'PerfCounters', nt.proxy({
  531. addCacheEvent: nt.func(null),
  532. getTime: nt.func(null),
  533. sendCacheEvents: nt.func(null),
  534. sendResTiming: nt.func(null),
  535. sendTimeMark: nt.func(null),
  536. __cacheEvents: []
  537. }));
  538. nt.define(Ya, '__isSent', true);
  539. nt.define(Ya, 'confirmUrl', '');
  540. nt.define(Ya, 'Direct', nt.proxy({
  541. insertInto: nt.func(null)
  542. }));
  543. nt.define(Ya, 'mediaCode', nt.proxy({
  544. create: function()
  545. {
  546. if (inIFrame)
  547. {
  548. console.log('Removed body of ad-frame.');
  549. document.documentElement.removeChild(document.body);
  550. }
  551. },
  552. moduleLoad: nt.func(null),
  553. setModule: nt.func(null)
  554. }));
  555. let extra = nt.proxy({
  556. extra: nt.proxy({ match: 0, confirm: '', src: '' }),
  557. id: 0, percent: 100, threshold: 1
  558. });
  559. nt.define(Ya, '_exp', nt.proxy({
  560. id: 0, coin: 0,
  561. choose: nt.func(extra),
  562. get: (prop) => extra.hasOwnProperty(prop) ? extra[prop] : null,
  563. getId: nt.func(0),
  564. defaultVersion: extra,
  565. getExtra: nt.func(extra.extra),
  566. getDefaultExtra: nt.func(extra.extra),
  567. versions: [extra]
  568. }));
  569. nt.define(Ya, 'c', nt.func(null));
  570. nt.define(Ya, 'ADBTools', function(){
  571. ['loadContext', 'testAdbStyle'].map(name => this[name] = nt.func(null));
  572. this.getCurrentState = nt.func(true);
  573. return nt.proxy(this);
  574. });
  575.  
  576. if (!location.hostname.includes('kinopoisk.ru')) {
  577. // kinopoisk uses adfox wrapped in Yandex code to display self-ads
  578. let adfoxCode = {};
  579. [
  580. 'create', 'reload',
  581. 'createAdaptive',
  582. 'createScroll'
  583. ].map(name => adfoxCode[name] = nt.func(null, name));
  584. nt.define(Ya, 'adfoxCode', nt.proxy(adfoxCode));
  585. } else {
  586. nt.define(win, 'abExperiments', nt.proxy([]));
  587. }
  588. let AdvManager = function()
  589. {
  590. [
  591. 'renderDirect',
  592. 'getBid', 'releaseBid',
  593. 'getSkipToken',
  594. 'getAdSessionId'
  595. ].map(name => this[name] = nt.func(null, name));
  596. this.render = function(o) {
  597. if (!o.renderTo)
  598. return;
  599. let placeholder = document.getElementById(o.renderTo);
  600. let parent = placeholder.parentNode;
  601. placeholder.style = 'display:none!important';
  602. parent.style = (parent.getAttribute('style')||'') + 'height:auto!important';
  603. // fix for Yandex TV pages
  604. if (location.hostname.startsWith('tv.yandex.'))
  605. {
  606. let sibling = placeholder.previousSibling;
  607. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  608. sibling.style.display = 'none';
  609. }
  610. };
  611. return nt.proxy(this);
  612. };
  613. nt.define(Ya, 'Context', nt.proxy({
  614. __longExperiment: null,
  615. _callbacks: nt.proxy([]),
  616. _asyncModeOn: true,
  617. _init: nt.func(null),
  618. AdvManager: new AdvManager()
  619. }));
  620. let Metrika = function()
  621. {
  622. [
  623. 'reachGoal', 'replacePhones',
  624. 'trackLinks', 'userParams',
  625. 'hit', 'params', 'clickmap'
  626. ].map(name => this[name] = nt.func(null, name));
  627. this.id = 0;
  628. return nt.proxy(this);
  629. };
  630. Metrika.counters = () => Ya._metrika.counters;
  631. nt.define(Ya, 'Metrika', Metrika);
  632. let counter = new Ya.Metrika();
  633. nt.define(Ya, '_metrika', nt.proxy({
  634. counter: counter,
  635. counters: [counter],
  636. hitParam: {},
  637. counterNum: 0,
  638. hitId: 0,
  639. v: 1
  640. }));
  641. nt.define(Ya, '_globalMetrikaHitId', 0);
  642. counter = {};
  643. [
  644. 'cpHitDelayed','wHitDelayed',
  645. 'hitDelayed','makeReq',
  646. 'redir','hit','log','cp','w'
  647. ].map(name => counter[name] = nt.func(null, name));
  648. [
  649. 'stringifyParams','_getVars',
  650. 'getUid','getUrl','getHash'
  651. ].map(name => counter[name] = nt.func(''));
  652. nt.define(Ya, 'counter', nt.proxy(counter));
  653. nt.define(Ya, 'jserrors', []);
  654. nt.define(Ya, 'onerror', nt.func());
  655. let Rum = {};
  656. [
  657. '__timeMarks', '__deltaMarks',
  658. '__defRes', '__defTimes', 'commonVars'
  659. ].map(name => Rum[name] = []);
  660. [
  661. 'sendTimeMark', 'sendResTiming', 'getTime',
  662. 'sendRaf', 'time', 'timeEnd', 'mark'
  663. ].map(name => Rum[name] = nt.func(null, name));
  664. nt.define(Ya, 'Rum', nt.proxy(Rum));
  665. for (let prop in Ya)
  666. YaProps.add(prop);
  667. nt.define(win, 'Ya', Ya);
  668. // Yandex.Metrika callbacks
  669. let yandex_metrika_callbacks = [];
  670. document.addEventListener(
  671. 'DOMContentLoaded',
  672. (e) => {
  673. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  674. yandex_metrika_callbacks.length = 0;
  675. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  676. },
  677. false
  678. );
  679. nt.define(win, 'yandex_metrika_callbacks', yandex_metrika_callbacks);
  680. }, nullTools
  681. );
  682.  
  683. // Creates and return protected style (unless protection is manually disabled).
  684. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  685. function createStyle(rules, props, skip_protect)
  686. {
  687. props = props || {};
  688. props.type = 'text/css';
  689.  
  690. function _protect(style)
  691. {
  692. if (skip_protect)
  693. return;
  694.  
  695. Object.defineProperty(style, 'sheet', {
  696. value: null,
  697. enumerable: true
  698. });
  699. Object.defineProperty(style, 'disabled', {
  700. get: () => true, //pretend to be disabled
  701. set: () => undefined,
  702. enumerable: true
  703. });
  704. (new MutationObserver(
  705. (ms) => _removeChild(ms[0].target)
  706. )).observe(style, { childList: true });
  707. }
  708.  
  709.  
  710. function _create()
  711. {
  712. let style = _appendChild(_createElement('style'));
  713. Object.assign(style, props);
  714.  
  715. function insertRules(rule)
  716. {
  717. if (rule.forEach)
  718. rule.forEach(insertRules);
  719. else try {
  720. style.sheet.insertRule(rule, 0);
  721. } catch (e) {
  722. console.error(e);
  723. }
  724. }
  725.  
  726. insertRules(rules);
  727. _protect(style);
  728.  
  729. return style;
  730. }
  731.  
  732. let style = _create();
  733. if (skip_protect)
  734. return style;
  735.  
  736. function resolveInANewContext(resolve)
  737. {
  738. setTimeout(
  739. (resolve) => resolve(_create()),
  740. 0, resolve
  741. );
  742. }
  743.  
  744. (new MutationObserver(
  745. function(ms)
  746. {
  747. let m, node;
  748. for (m of ms) for (node of m.removedNodes)
  749. if (node === style)
  750. (new Promise(resolveInANewContext))
  751. .then((st) => (style = st));
  752. }
  753. )).observe(_de, { childList: true });
  754.  
  755. return style;
  756. }
  757.  
  758. // https://greasyfork.org/scripts/19144-websuckit/
  759. function useWSI()
  760. {
  761. // check does browser support Proxy and WebSocket
  762. if (typeof Proxy !== 'function' ||
  763. typeof WebSocket !== 'function')
  764. return;
  765.  
  766. function getWrappedCode()
  767. {
  768. let text = getWrappedCode.toString() + WSI.toString();
  769. return `(function(){"use strict";${(
  770. text.replace(/\/\/[^\r\n]*/g,'').replace(/[\s\r\n]+/g,' ')
  771. )}(new WSI(self||window)).init();})();\n`;
  772. }
  773.  
  774. function WSI(win, safeWin)
  775. {
  776. safeWin = safeWin || win;
  777. let masks = [], filter;
  778. for (filter of [// blacklist
  779. '||185.87.50.147^',
  780. '||10root25.website^', '||24video.xxx^',
  781. '||adlabs.ru^', '||adspayformymortgage.win^', '||aviabay.ru^',
  782. '||bgrndi.com^', '||brokeloy.com^',
  783. '||cnamerutor.ru^',
  784. '||docfilms.info^', '||dreadfula.ru^',
  785. '||et-code.ru^', '||etcodes.com^',
  786. '||franecki.net^', '||film-doma.ru^',
  787. '||free-torrent.org^', '||free-torrent.pw^',
  788. '||free-torrents.org^', '||free-torrents.pw^',
  789. '||game-torrent.info^', '||gocdn.ru^',
  790. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  791. '||joyreactor.cc^', '||pornreactor.cc^', '||reactor.cc^',
  792. '||kiev.ua^', '||kinotochka.net^',
  793. '||kinott.com^', '||kinott.ru^', '||kuveres.com^',
  794. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  795. '||mail.ru^', '||marketgid.com^', '||mixadvert.com^', '||mxtads.com^',
  796. '||nickhel.com^',
  797. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  798. '||pkpojhc.com^',
  799. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  800. '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  801. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  802. '||skidl.ru^',
  803. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||ttarget.ru^',
  804. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  805. '||xxuhter.ru^',
  806. '||yuiout.online^',
  807. '||zoom-film.ru^'])
  808. masks.push(new RegExp(
  809. filter.replace(/([\\\/\[\].*+?(){}$])/g, '\\$1')
  810. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  811. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  812. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^\/.]+\\.)*'),
  813. 'i'));
  814.  
  815. function isBlocked(url) {
  816. for (let mask of masks)
  817. if (mask.test(url))
  818. return true;
  819. return false;
  820. }
  821.  
  822. function wrapWebSocket(wsParent)
  823. {
  824. let _WebSocket = wsParent.WebSocket;
  825. // getter for properties of fake WS, returns fake functions
  826. // if there are functions with such name in the real WS and
  827. // also returns constants from real WS
  828. function wsGetter(target, name)
  829. {
  830. try {
  831. if (typeof _WebSocket.prototype[name] === 'function')
  832. {
  833. if (name === 'close' || name === 'send') // send also closes connection
  834. target.readyState = _WebSocket.CLOSED;
  835. return (
  836. function fake() {
  837. console.warn(`[WSI] Invoked function "${name}"`);
  838. return;
  839. }
  840. );
  841. }
  842. if (typeof _WebSocket.prototype[name] === 'number')
  843. return _WebSocket[name];
  844. } catch(ignore) {}
  845. return target[name];
  846. }
  847. // Wrap WS object
  848. wsParent.WebSocket = new Proxy(_WebSocket, {
  849. construct: function (target, args)
  850. {
  851. let url = args[0];
  852. console.log(`[WSI] Opening socket on ${url}\u2026`);
  853. if (isBlocked(url))
  854. {
  855. console.log("[WSI] Blocked.");
  856. return new Proxy({
  857. url: url,
  858. readyState: _WebSocket.OPEN
  859. }, {
  860. get: wsGetter,
  861. set: () => true
  862. });
  863. }
  864. return Reflect.construct(target, args);
  865. }
  866. });
  867. }
  868.  
  869. function WorkerWrapper()
  870. {
  871. let realWorker = win.Worker;
  872. win.Worker = function Worker() {
  873. let isBlobURL = /^blob:/i,
  874. resourceURI = arguments[0],
  875. deepLogMode = false,
  876. _callbacks = new WeakMap(),
  877. _worker = null,
  878. _onevs = { names: ['onmessage', 'onerror'] },
  879. _actions = [],
  880. _self = this;
  881.  
  882. function log()
  883. {
  884. if (deepLogMode)
  885. console.log.apply(_self, arguments);
  886. }
  887.  
  888. function callbackWrapper(func)
  889. {
  890. if (typeof func !== 'function')
  891. return undefined;
  892.  
  893. return function callback()
  894. {
  895. return func.apply(_self, arguments);
  896. };
  897. }
  898.  
  899. function updateWorker()
  900. {
  901. for (let [action, name, args] of _actions) {
  902. log(_worker, action, name, args);
  903. if (action === 'set')
  904. _worker[name] = callbackWrapper(args);
  905. if (action === 'call')
  906. _worker[name].apply(_worker, args);
  907. }
  908. _actions.length = 0;
  909. log('Applied buffered actions.');
  910. }
  911.  
  912. for (let prop of _onevs.names)
  913. Object.defineProperty(_self, prop, {
  914. set: function(...args) {
  915. let val = args[0];
  916. _onevs[prop] = val;
  917. if (_worker)
  918. _worker[prop] = callbackWrapper(val);
  919. else {
  920. _actions.push(['set', prop, val]);
  921. log('Stored into buffer:', args);
  922. }
  923. },
  924. get: () => _onevs[prop],
  925. enumerable: true
  926. });
  927.  
  928. _self.postMessage = function(...args)
  929. {
  930. if (_worker)
  931. _worker.postMessage.apply(_worker, args);
  932. else {
  933. _actions.push(['call', 'postMessage', args]);
  934. log('Stored into buffer:', args);
  935. }
  936. };
  937. _self.terminate = function(...args)
  938. {
  939. if (_worker)
  940. _worker.terminate();
  941. else {
  942. _actions.push(['call','terminate', args]);
  943. log('Stored into buffer:', args);
  944. }
  945. };
  946. _self.addEventListener = function(...args)
  947. {
  948. let [event, callback, other] = args;
  949. if (typeof callback !== 'function')
  950. return;
  951.  
  952. if (!_callbacks.has(callback))
  953. _callbacks.set(callback, callbackWrapper(callback));
  954.  
  955. args[1] = _callbacks.get(callback);
  956. if (_worker)
  957. _worker.addEventListener.apply(_worker, args);
  958. else {
  959. _actions.push(['call', 'addEventListener', args]);
  960. log('Stored into buffer:', args);
  961. }
  962. };
  963. _self.removeEventListener = function(...args)
  964. {
  965. let [event, callback, other] = args;
  966. if (typeof callback !== 'function' || !_callbacks.has(callback))
  967. return;
  968.  
  969. args[1] = _callbacks.get(callback);
  970. _callbacks.delete(callback);
  971. if (_worker)
  972. _worker.removeEventListener.apply(_worker, args);
  973. else {
  974. _actions.push(['call', 'removeEventListener', args]);
  975. log('Stored into buffer:', args);
  976. }
  977. };
  978.  
  979. if (!isBlobURL.test(resourceURI))
  980. {
  981. _worker = new realWorker(resourceURI);
  982. return; // not a blob, no need to wrap
  983. }
  984.  
  985. (new Promise(
  986. function(resolve, reject)
  987. {
  988. let xhr = new XMLHttpRequest();
  989. xhr.responseType = 'blob';
  990. try {
  991. xhr.open('GET', resourceURI, true);
  992. } catch(e) {
  993. return reject(e);
  994. }
  995. if (xhr.readyState !== XMLHttpRequest.OPENED) {
  996. // connection wasn't opened, unable to continue wrapping procedure
  997. return reject(xhr.readyState);
  998. }
  999. xhr.onload = function(e)
  1000. {
  1001. if (e.target.status === 200)
  1002. {
  1003. let reader = new FileReader();
  1004. reader.addEventListener(
  1005. 'loadend', function(e)
  1006. {
  1007. resolve(
  1008. new realWorker(URL.createObjectURL(
  1009. new Blob([getWrappedCode() + e.target.result])
  1010. ))
  1011. );
  1012. }, false
  1013. );
  1014. reader.readAsText(e.target.response);
  1015. } else {
  1016. return reject(e);
  1017. }
  1018. };
  1019. xhr.onerror = (e) => reject(e);
  1020. xhr.send();
  1021. }
  1022. )).then(
  1023. function(val)
  1024. {
  1025. _worker = val;
  1026. updateWorker();
  1027. }
  1028. ).catch(
  1029. function(e)
  1030. {
  1031. // connection were blocked by CSP or something else triggered error event on xhr object
  1032. // unable to proceed with wrapper, return object as-is
  1033. _worker = new realWorker(resourceURI);
  1034. updateWorker();
  1035. }
  1036. );
  1037.  
  1038. if (deepLogMode)
  1039. {
  1040. return new Proxy(_self, {
  1041. get: function(target, prop) {
  1042. console.log(`Get Worker.${prop}`);
  1043. return target[prop];
  1044. },
  1045. set: function(target, prop, val) {
  1046. console.log(`Set Worker.${prop} = ${val}`);
  1047. target[prop] = val;
  1048. return true;
  1049. }
  1050. });
  1051. }
  1052. }.bind(safeWin);
  1053.  
  1054. realWorker.prototype.constructor = win.Worker;
  1055. win.Worker.prototype = realWorker.prototype;
  1056. }
  1057.  
  1058. function CreateElementWrapper()
  1059. {
  1060. let key = `_${Math.random().toString(36).substr(2)}`,
  1061. _createElement = Document.prototype.createElement,
  1062. _addEventListener = Element.prototype.addEventListener,
  1063. isDataURL = /^data:/i,
  1064. isBlobURL = /^blob:/i;
  1065.  
  1066. // IFrame SRC get/set wrapper
  1067. let ifGetSet = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
  1068. if (ifGetSet)
  1069. {
  1070. let code = encodeURIComponent(`<script>${getWrappedCode()}</script>\n`),
  1071. dataSrc = new WeakMap(),
  1072. _ifSet = ifGetSet.set,
  1073. _ifGet = ifGetSet.get;
  1074. ifGetSet.set = function(val)
  1075. {
  1076. if (this[key] && val === dataSrc.get(this))
  1077. { // if already processed data URL then do nothing
  1078. delete this[key];
  1079. return null;
  1080. }
  1081. let isData = isDataURL.test(val);
  1082. if (isData && val.indexOf(code) < 0)
  1083. {
  1084. dataSrc.set(this, val);
  1085. val = val.replace(',', `,${code}`);
  1086. }
  1087. if (!isData && dataSrc.get(this))
  1088. dataSrc.delete(this);
  1089. return _ifSet.call(this, val);
  1090. };
  1091. ifGetSet.get = function()
  1092. {
  1093. return dataSrc.get(this) || _ifGet.call(this);
  1094. };
  1095. Object.defineProperty(HTMLIFrameElement.prototype, 'src', ifGetSet);
  1096. }
  1097.  
  1098. function frameSetWSWrapper(e)
  1099. {
  1100. let frm = e.target;
  1101. try {
  1102. if (!frm.src || isBlobURL.test(frm.src))
  1103. wrapWebSocket(frm.contentWindow);
  1104. } catch (ignore) {}
  1105. }
  1106.  
  1107. let scriptMap = new WeakMap();
  1108. scriptMap.isBlocked = isBlocked;
  1109. let onErrorWrapper = {
  1110. set: function(val)
  1111. {
  1112. if (scriptMap.has(this))
  1113. {
  1114. this.removeEventListener('error', scriptMap.get(this).wrp, false);
  1115. scriptMap.delete(this);
  1116. }
  1117. if (!val || typeof val !== 'function')
  1118. return val;
  1119.  
  1120. scriptMap.set(this, {
  1121. org: val,
  1122. wrp: function(...args)
  1123. {
  1124. if (scriptMap.isBlocked(this.src))
  1125. console.log('[WSI] Blocked "onerror" callback from', this.src);
  1126. else
  1127. scriptMap.get(this).org.apply(this, args);
  1128. }
  1129. });
  1130. this.addEventListener('error', scriptMap.get(this).wrp, false);
  1131. },
  1132. get: function()
  1133. {
  1134. return scriptMap.has(this) ? scriptMap.get(this).org : null;
  1135. },
  1136. enumerable: true
  1137. };
  1138. Document.prototype.createElement = function createElement(...args) {
  1139. let el = _createElement.apply(this, args);
  1140.  
  1141. if (el.tagName === 'IFRAME')
  1142. _addEventListener.call(el, 'load', frameSetWSWrapper, false);
  1143. if (el.tagName === 'SCRIPT')
  1144. Object.defineProperty(el, 'onerror', onErrorWrapper);
  1145.  
  1146. return el;
  1147. };
  1148.  
  1149. document.addEventListener(
  1150. 'DOMContentLoaded', function()
  1151. {
  1152. for (let ifr of document.querySelectorAll('IFRAME'))
  1153. {
  1154. if (isDataURL.test(ifr.src))
  1155. {
  1156. ifr[key] = true;
  1157. ifr.src = ifr.src; // call setter and let it do the job
  1158. }
  1159. _addEventListener.call(ifr, 'load', frameSetWSWrapper, false);
  1160. }
  1161. }, false
  1162. );
  1163. }
  1164.  
  1165. this.init = function()
  1166. {
  1167. wrapWebSocket(win);
  1168. if (!(/firefox/i.test(navigator.userAgent))) // skip WorkerWrapper in Firefox
  1169. (new Promise(
  1170. function(resolve, reject)
  1171. { // test is it possible to run inline scripts
  1172. if (self.constructor.name.indexOf('Worker') > -1)
  1173. return resolve(); // running within a Worker
  1174. let onerr = window.onerror,
  1175. onscr = (e) => resolve();
  1176. // for some reason addEventListener on 'error' doesn't catch this error
  1177. window.onerror = (e) => reject(e);
  1178. window.addEventListener('inlineSuccess', onscr, false);
  1179. let scr = document.createElement('script');
  1180. scr.textContent = "window.dispatchEvent(new Event('inlineSuccess'));";
  1181. document.documentElement.appendChild(scr);
  1182. document.documentElement.removeChild(scr);
  1183. window.removeEventListener('inlineSuccess', onscr, false);
  1184. window.onerror = onerr;
  1185. }
  1186. )).then(
  1187. (e) => WorkerWrapper()
  1188. ).catch(
  1189. (e) => console.log('[WSI] Unable to create inline script. Skipping Worker wrapper to avoid further issues.', e)
  1190. );
  1191. if (typeof document !== 'undefined')
  1192. CreateElementWrapper();
  1193. };
  1194. }
  1195.  
  1196. if (isFirefox)
  1197. {
  1198. let script = _createElement('script');
  1199. script.textContent = getWrappedCode();
  1200. _appendChild(script);
  1201. _removeChild(script);
  1202. return; //we don't want to call functions on page from here in Fx, so exit
  1203. }
  1204.  
  1205. (new WSI((unsafeWindow||self||window),(self||window))).init();
  1206. }
  1207.  
  1208. if (!isFirefox)
  1209. { // scripts for non-Firefox browsers
  1210. // https://greasyfork.org/scripts/14720-it-s-not-important
  1211. {
  1212. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  1213. ret_b = (a,b) => b,
  1214. _toLowerCase = String.prototype.toLowerCase,
  1215. protectedNodes = new WeakSet(),
  1216. log = false;
  1217.  
  1218. let logger = function()
  1219. {
  1220. if (log)
  1221. console.log('Some page elements became a bit less important.');
  1222. log = false;
  1223. };
  1224.  
  1225. let unimportanter = function(node)
  1226. {
  1227. let style = (node.nodeType === Node.ELEMENT_NODE) ?
  1228. _getAttribute.call(node, 'style') : null;
  1229.  
  1230. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  1231. (node.src && node.src.slice(0,17) === 'chrome-extension:')) // Web of Trust IFRAME and similar
  1232. return false; // get out if we have nothing to do here
  1233.  
  1234. protectedNodes.add(node);
  1235. _setAttribute.call(node, 'style',
  1236. style.replace(imptt, ret_b));
  1237. log = true;
  1238. };
  1239.  
  1240. (new MutationObserver(
  1241. function(mutations)
  1242. {
  1243. setTimeout(
  1244. function(ms)
  1245. {
  1246. let m, node;
  1247. for (m of ms) for (node of m.addedNodes)
  1248. unimportanter(node);
  1249. logger();
  1250. }, 0, mutations
  1251. );
  1252. }
  1253. )).observe(document, {
  1254. childList : true,
  1255. subtree : true
  1256. });
  1257.  
  1258. Element.prototype.setAttribute = function setAttribute(name, value)
  1259. {
  1260. "[native code]";
  1261. let replaced = value;
  1262. if (_toLowerCase.call(name) === 'style' && protectedNodes.has(this))
  1263. replaced = value.replace(imptt, ret_b);
  1264. log = (replaced !== value);
  1265. logger();
  1266. return _setAttribute.call(this, name, replaced);
  1267. };
  1268.  
  1269. win.addEventListener (
  1270. 'load', function()
  1271. {
  1272. for (let imp of document.querySelectorAll('[style*="!"]'))
  1273. unimportanter(imp);
  1274. logger();
  1275. }, false
  1276. );
  1277. }
  1278.  
  1279. // Naive ABP Style protector
  1280. {
  1281. let _querySelector = Document.prototype.querySelector.bind(document);
  1282. let _removeChild = Node.prototype.removeChild;
  1283. let _appendChild = Node.prototype.appendChild;
  1284. let createShadow = () => _createElement('shadow');
  1285. // Prevent adding fake content entry point
  1286. Node.prototype.appendChild = function(child)
  1287. {
  1288. if (this instanceof ShadowRoot &&
  1289. child instanceof HTMLContentElement)
  1290. return _appendChild.call(this, createShadow());
  1291. return _appendChild.apply(this, arguments);
  1292. };
  1293. {
  1294. let _shadowSelector = ShadowRoot.prototype.querySelector;
  1295. let _innerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
  1296. let _parentNode = Object.getOwnPropertyDescriptor(Node.prototype, 'parentNode');
  1297. if (_innerHTML && _parentNode)
  1298. {
  1299. let _set = _innerHTML.set;
  1300. let _getParent = _parentNode.get;
  1301. _innerHTML.configurable = false;
  1302. _innerHTML.set = function()
  1303. {
  1304. _set.apply(this, arguments);
  1305. let content = _shadowSelector.call(this, 'content');
  1306. if (content)
  1307. {
  1308. let parent = _getParent.call(content);
  1309. _removeChild.call(parent, content);
  1310. _appendChild.call(parent, createShadow());
  1311. }
  1312. };
  1313. }
  1314. Object.defineProperty(ShadowRoot.prototype, 'innerHTML', _innerHTML);
  1315. }
  1316. // Locate and apply extra protection to a style on top of what ABP does
  1317. let style;
  1318. (new Promise(
  1319. function(resolve, reject)
  1320. {
  1321. let getStyle = () => _querySelector('::shadow style');
  1322. style = getStyle();
  1323. if (style)
  1324. return resolve(style);
  1325. let intv = setInterval(
  1326. function()
  1327. {
  1328. style = getStyle();
  1329. if (!style)
  1330. return;
  1331. intv = clearInterval(intv);
  1332. return resolve(style);
  1333. }, 0
  1334. );
  1335. document.addEventListener(
  1336. 'DOMContentLoaded',
  1337. function()
  1338. {
  1339. if (intv)
  1340. clearInterval(intv);
  1341. style = getStyle();
  1342. return style ? resolve(style) : reject();
  1343. },
  1344. false
  1345. );
  1346. }
  1347. )).then(
  1348. function(style)
  1349. {
  1350. let emptyArr = [],
  1351. nullStr = {
  1352. get: () => '',
  1353. set: () => undefined
  1354. };
  1355. Object.defineProperties(style, {
  1356. innerHTML: nullStr,
  1357. textContent: nullStr
  1358. });
  1359. Object.defineProperties(style.sheet, {
  1360. deleteRule: () => null,
  1361. cssRules: emptyArr,
  1362. rules: emptyArr
  1363. });
  1364. }
  1365. ).catch(()=>null);
  1366. Node.prototype.removeChild = function(child)
  1367. {
  1368. if (child === style)
  1369. return;
  1370. return _removeChild.apply(this, arguments);
  1371. };
  1372. }
  1373. }
  1374. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/i.test(win.location.href) ||
  1375. /^https?:\/\/tv\.yandex\./i.test(win.location.href))
  1376. {
  1377. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  1378. let yadWord = /Яндекс.Директ/i,
  1379. adWords = /Реклама|Ad/i;
  1380. let _querySelector = document.querySelector.bind(document),
  1381. _querySelectorAll = document.querySelectorAll.bind(document),
  1382. _getAttribute = Element.prototype.getAttribute,
  1383. _setAttribute = Element.prototype.setAttribute;
  1384. // Function to attach an observer to monitor dynamic changes on the page
  1385. let pageUpdateObserver = (func, obj, params) => {
  1386. if (obj)
  1387. (new MutationObserver(func))
  1388. .observe(obj, (params || { childList:true, subtree:true }));
  1389. };
  1390. // Short name for parentNode.removeChild
  1391. let remove = (node) => {
  1392. if (!node || !node.parentNode)
  1393. return false;
  1394. console.log('Removed node.');
  1395. node.parentNode.removeChild(node);
  1396. };
  1397. // Yandex search ads in Google Chrome
  1398. if ('attachShadow' in Element.prototype)
  1399. {
  1400. let _attachShadow = Element.prototype.attachShadow;
  1401. Element.prototype.attachShadow = function()
  1402. {
  1403. let node = this,
  1404. root = _attachShadow.apply(node, arguments);
  1405. pageUpdateObserver(
  1406. (ms) => {
  1407. for (let m of ms) if (m.addedNodes.length)
  1408. if (adWords.test(root.textContent))
  1409. remove(node.closest('.serp-item'));
  1410. }, root
  1411. );
  1412. return root;
  1413. };
  1414. }
  1415. // prevent/defuse adblock detector
  1416. setInterval(()=>{
  1417. localStorage.ic = '';
  1418. localStorage._mt__data = '';
  1419. },100);
  1420. let _doc_proto = ('cookie' in Document.prototype) ? Document.prototype : Object.getPrototypeOf(document);
  1421. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  1422. if (_cookie)
  1423. {
  1424. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  1425. _cookie.set = function(value)
  1426. {
  1427. if (/^(mda=|yp=|ys=|yabs-|__)/.test(value))
  1428. {
  1429. // remove value, set expired
  1430. if (!value.startsWith('yp=')) {
  1431. value = value.replace(/^([^=]+=)[^;]+/,'$1').replace(/(expires=)[\w\s\d,]+/,'$1Thu, 01 Jan 1970 00');
  1432. console.log('expire cookie', value.match(/^[^=]+/)[0]);
  1433. } else {
  1434. let parts = value.split(';');
  1435. let values = parts[0].split('#').filter(part => /\.sp\./.test(part));
  1436. if (values.length)
  1437. values[0] = values[0].replace(/^yp=/, '');
  1438. parts[0] = `yp=${values.join('#')}`;
  1439. value = parts.join(';');
  1440. console.log(`set cookie ${parts[0]}`);
  1441. }
  1442. //return null;
  1443. }
  1444. return _set_cookie(this, value);
  1445. };
  1446. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  1447. }
  1448. // other ads
  1449. document.addEventListener(
  1450. 'DOMContentLoaded', function()
  1451. {
  1452. { // Generic ads removal and fixes
  1453. let node = _querySelector('.serp-header');
  1454. if (node)
  1455. node.style.marginTop = '0';
  1456. for (node of _querySelectorAll(
  1457. '.serp-adv__head + .serp-item,'+
  1458. '#adbanner,'+
  1459. '.serp-adv,'+
  1460. '.b-spec-adv,'+
  1461. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  1462. )) remove(node);
  1463. }
  1464. // Search ads
  1465. function removeSearchAds()
  1466. {
  1467. for (let node of _querySelectorAll('.serp-item'))
  1468. if (_getAttribute.call(node, 'role') === 'complementary' ||
  1469. adWords.test((node.querySelector('.label')||{}).textContent))
  1470. remove(node);
  1471. }
  1472. // News ads
  1473. function removeNewsAds()
  1474. {
  1475. let node, block, item, items, mask, classes,
  1476. masks = [
  1477. { class: '.ads__wrapper', regex: /[^,]*?,[^,]*?\.ads__wrapper/ },
  1478. { class: '.ads__pool', regex: /[^,]*?,[^,]*?\.ads__pool/ }
  1479. ];
  1480. for (node of _querySelectorAll('style[nonce]'))
  1481. {
  1482. classes = node.innerText.replace(/\{[^}]+\}+/ig, '|').split('|');
  1483. for (block of classes) for (mask of masks)
  1484. if (block.includes(mask.class))
  1485. {
  1486. block = block.match(mask.regex)[0];
  1487. items = _querySelectorAll(block);
  1488. for (item of items)
  1489. remove(items[0]);
  1490. }
  1491. }
  1492. }
  1493. // Music ads
  1494. function removeMusicAds()
  1495. {
  1496. for (let node of _querySelectorAll('.ads-block'))
  1497. remove(node);
  1498. }
  1499. // Mail ads
  1500. function removeMailAds()
  1501. {
  1502. let slice = Array.prototype.slice,
  1503. nodes = slice.call(_querySelectorAll('.ns-view-folders')),
  1504. node, len, cls;
  1505.  
  1506. for (node of nodes)
  1507. if (!len || len > node.classList.length)
  1508. len = node.classList.length;
  1509.  
  1510. node = nodes.pop();
  1511. while (node)
  1512. {
  1513. if (node.classList.length > len)
  1514. for (cls of slice.call(node.classList))
  1515. if (cls.indexOf('-') === -1)
  1516. {
  1517. remove(node);
  1518. break;
  1519. }
  1520. node = nodes.pop();
  1521. }
  1522. }
  1523. // News fixes
  1524. function removePageAdsClass()
  1525. {
  1526. if (document.body.classList.contains("b-page_ads_yes"))
  1527. {
  1528. document.body.classList.remove("b-page_ads_yes");
  1529. console.log('Page ads class removed.');
  1530. }
  1531. }
  1532. // TV fixes
  1533. function removeTVAds()
  1534. {
  1535. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  1536. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])'))
  1537. {
  1538. if (node.offsetWidth)
  1539. {
  1540. let pad = document.createElement('div');
  1541. _setAttribute.call(pad, 'style', `width:${node.offsetWidth}px`);
  1542. node.parentNode.appendChild(pad);
  1543. }
  1544. remove(node);
  1545. }
  1546. }
  1547.  
  1548. if (location.hostname.startsWith('mail.')) {
  1549. pageUpdateObserver(
  1550. function(ms, o)
  1551. {
  1552. let aside = _querySelector('.mail-Layout-Aside');
  1553. if (aside) {
  1554. o.disconnect();
  1555. pageUpdateObserver(removeMailAds, aside);
  1556. }
  1557. }, document.body
  1558. );
  1559. removeMailAds();
  1560. } else if (location.hostname.startsWith('music.')) {
  1561. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1562. removeMusicAds();
  1563. } else if (location.hostname.startsWith('news.')) {
  1564. pageUpdateObserver(removeNewsAds, document.body);
  1565. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1566. removeNewsAds();
  1567. removePageAdsClass();
  1568. } else if (location.hostname.startsWith('tv.')) {
  1569. pageUpdateObserver(removeTVAds, document.body);
  1570. removeTVAds();
  1571. } else {
  1572. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  1573. removeSearchAds();
  1574. }
  1575. }
  1576. );
  1577. }
  1578.  
  1579. // Yandex Link Tracking
  1580. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1581. {
  1582. scriptLander(() => {
  1583. let nt = new nullTools({log: false});
  1584. let AwapsJsonAPI_Json = nt.proxy({
  1585. prototype: nt.proxy({
  1586. setID: nt.proxy(nt.func(null, 'setID')),
  1587. checkBannerVisibility: nt.proxy(nt.func(true, 'checkBannerVisibility')),
  1588. addIframeContent: nt.proxy(function(...args) {
  1589. try {
  1590. let frame = args[1][0].parentNode;
  1591. frame.parentNode.removeChild(frame);
  1592. console.log(`Removed banner placeholder.`);
  1593. } catch(ignore) {
  1594. console.log(`Can't locate frame object to remove.`);
  1595. }
  1596. }),
  1597. addImageContent: nt.proxy(nt.func(null, 'addImageContent')),
  1598. sendCounts: nt.proxy(nt.func(null, 'sendCounts')),
  1599. getHTML: nt.proxy(nt.func('', 'getHTML')),
  1600. expand: nt.proxy(nt.func(null, 'expand'))
  1601. })
  1602. });
  1603. if ('AwapsJsonAPI' in win) {
  1604. console.log('Oops! AwapsJsonAPI already defined.');
  1605. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1606. } else {
  1607. nt.define(win, 'AwapsJsonAPI', nt.proxy({
  1608. Json: AwapsJsonAPI_Json
  1609. }));
  1610. }
  1611.  
  1612. let home = win.home || {};
  1613. let parseExport = x => {
  1614. if (!x)
  1615. return x;
  1616. // remove banner placeholder
  1617. if (x.banner && x.banner.cls) {
  1618. let banners = document.querySelectorAll('.' + x.banner.cls.banner__parent);
  1619. for (let banner of banners) {
  1620. _setAttribute.call(banner, 'style', 'display:none!important');
  1621. console.log('Hid banner placeholder.');
  1622. }
  1623. }
  1624.  
  1625. // remove banner data and some other stuff
  1626. delete x.banner;
  1627. delete x.consistency;
  1628. delete x['i-bannerid'];
  1629. delete x['i-counter'];
  1630. delete x['ga-counter'];
  1631. delete x['promo-curtain'];
  1632.  
  1633. return x;
  1634. };
  1635. let home_export = parseExport(home.export);
  1636. Object.defineProperty(home, 'export', {
  1637. get: x => home_export,
  1638. set: x => {
  1639. home_export = parseExport(x);
  1640. }
  1641. });
  1642. nt.define(win, 'home', home);
  1643. }, nullTools);
  1644.  
  1645. if ('attachShadow' in Element.prototype) {
  1646. let fakeRoot = () => ({
  1647. firstChild: null,
  1648. appendChild: ()=>null,
  1649. querySelector: ()=>null,
  1650. querySelectorAll: ()=>null
  1651. });
  1652. Element.prototype.createShadowRoot = fakeRoot;
  1653. let shadows = new WeakMap();
  1654. let _attachShadow = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
  1655. let _call_attachShadow = _attachShadow.value;
  1656. _attachShadow.value = function() {
  1657. return shadows.set(this, fakeRoot()).get(this);
  1658. };
  1659. Object.defineProperty(Element.prototype, 'attachShadow', _attachShadow);
  1660. let _shadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot');
  1661. _shadowRoot.set = () => null;
  1662. _shadowRoot.get = function() {
  1663. return shadows.has(this) ? shadows.get(this) : void 0;
  1664. };
  1665. Object.defineProperty(Element.prototype, 'shadowRoot', _shadowRoot);
  1666. }
  1667. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1668. let selectors = (
  1669. 'A[onmousedown*="/jsredir"],'+
  1670. 'A[data-vdir-href],'+
  1671. 'A[data-counter]'
  1672. );
  1673. let removeTrackingAttributes = function(link)
  1674. {
  1675. link.removeAttribute('onmousedown');
  1676. if (link.hasAttribute('data-vdir-href')) {
  1677. link.removeAttribute('data-vdir-href');
  1678. link.removeAttribute('data-orig-href');
  1679. }
  1680. if (link.hasAttribute('data-counter')) {
  1681. link.removeAttribute('data-counter');
  1682. link.removeAttribute('data-bem');
  1683. }
  1684. };
  1685. let removeTracking = function(scope)
  1686. {
  1687. for (let link of scope.querySelectorAll(selectors))
  1688. removeTrackingAttributes(link);
  1689. };
  1690. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1691. (new MutationObserver(
  1692. function(ms)
  1693. {
  1694. let m, node;
  1695. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1696. if (node.tagName === 'A' && node.matches(selectors)) {
  1697. removeTrackingAttributes(node);
  1698. } else {
  1699. removeTracking(node);
  1700. }
  1701. }
  1702. )).observe(_de, { childList: true, subtree: true });
  1703.  
  1704. //skip fixes for other sites
  1705. return;
  1706. }
  1707.  
  1708. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1709. document.addEventListener(
  1710. 'DOMContentLoaded', function()
  1711. {//createPlayer();
  1712. function log (name) {
  1713. console.log(`Player FIX: Detected ${name} player on ${location.href}`);
  1714. }
  1715. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1716. {
  1717. log('Moonwalk');
  1718. if (win.adv_enabled)
  1719. win.adv_enabled = false;
  1720. win.condition_detected = false;
  1721. if (win.MXoverrollCallback)
  1722. document.addEventListener(
  1723. 'click', function catcher(e)
  1724. {
  1725. e.stopPropagation();
  1726. win.MXoverrollCallback.call(window);
  1727. document.removeEventListener('click', catcher, true);
  1728. }, true
  1729. );
  1730. }
  1731. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1732. {
  1733. log('HDGo');
  1734. document.body.onclick = null;
  1735. let tmp = document.querySelector('#swtf');
  1736. if (tmp)
  1737. tmp.style.display = 'none';
  1738. if (win.banner_second !== undefined)
  1739. win.banner_second = 0;
  1740. if (win.$banner_ads !== undefined)
  1741. win.$banner_ads = false;
  1742. if (win.$new_ads !== undefined)
  1743. win.$new_ads = false;
  1744. if (win.createCookie !== undefined)
  1745. win.createCookie('popup', 'true', '999');
  1746. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1747. win.canRunAds = true;
  1748. }
  1749. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1750. {
  1751. log('Kodik');
  1752. let tmp = document.querySelector('.play_button');
  1753. if (tmp)
  1754. tmp.onclick = win.MXoverrollCallback.bind(window);
  1755. win.IsAdBlock = false;
  1756. }
  1757. else if (win.getnextepisode && win.uppodEvent)
  1758. {
  1759. log('Share-Serials.net');
  1760. scriptLander(
  1761. function()
  1762. {
  1763. let _setInterval = win.setInterval,
  1764. _setTimeout = win.setTimeout;
  1765. win.setInterval = function(func)
  1766. {
  1767. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1768. {
  1769. let intv = _setInterval.call(
  1770. this, function()
  1771. {
  1772. _setTimeout.call(
  1773. this, function(intv)
  1774. {
  1775. clearInterval(intv);
  1776. let timer = document.querySelector('#timer');
  1777. if (timer)
  1778. timer.click();
  1779. }, 100, intv);
  1780. func.call(this);
  1781. }, 5
  1782. );
  1783.  
  1784. return intv;
  1785. }
  1786. return _setInterval.apply(this, arguments);
  1787. };
  1788. win.setTimeout = function(func) {
  1789. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1790. {
  1791. return _setTimeout.call(this, func, 0);
  1792. }
  1793. return _setTimeout.apply(this, arguments);
  1794. };
  1795. }
  1796. );
  1797. } else if ('ADC' in win)
  1798. {
  1799. log('vjs-creatives plugin in');
  1800. let replacer = (obj) => {
  1801. for (let name in obj)
  1802. if (obj[name] instanceof Function)
  1803. obj[name] = () => null;
  1804. };
  1805. replacer(win.ADC);
  1806. replacer(win.currentAdSlot);
  1807. }
  1808. }, false
  1809. );
  1810.  
  1811. // piguiqproxy.com circumvention prevention
  1812. scriptLander(
  1813. function()
  1814. {
  1815. let _open = XMLHttpRequest.prototype.open;
  1816. let blacklist = /[/.@](piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1817. XMLHttpRequest.prototype.open = function(method, url)
  1818. {
  1819. if (method === 'GET' && blacklist.test(url))
  1820. {
  1821. this.send = () => null;
  1822. this.setRequestHeader = () => null;
  1823. console.log('Blocked request: ', url);
  1824. return;
  1825. }
  1826. return _open.apply(this, arguments);
  1827. };
  1828. }
  1829. );
  1830.  
  1831. // === Helper functions ===
  1832.  
  1833. // function to search and remove nodes by content
  1834. // selector - standard CSS selector to define set of nodes to check
  1835. // words - regular expression to check content of the suspicious nodes
  1836. // params - object with multiple extra parameters:
  1837. // .log - display log in the console
  1838. // .hide - set display to none instead of removing from the page
  1839. // .parent - parent node to remove if content is found in the child node
  1840. // .siblings - number of simling nodes to remove (excluding text nodes)
  1841. let scRemove = (node) => node.parentNode.removeChild(node);
  1842. let scHide = function(node)
  1843. {
  1844. let style = _getAttribute.call(node, 'style') || '',
  1845. hide = ';display:none!important;';
  1846. if (style.indexOf(hide) < 0)
  1847. _setAttribute.call(node, 'style', style + hide);
  1848. };
  1849.  
  1850. function scissors (selector, words, scope, params)
  1851. {
  1852. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1853. if (!scope.contains(document.body))
  1854. logger('[s] scope', scope);
  1855. let remFunc = (params.hide ? scHide : scRemove),
  1856. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1857. toRemove = [],
  1858. siblings;
  1859. for (let node of scope.querySelectorAll(selector))
  1860. {
  1861. // drill up to a parent node if specified, break if not found
  1862. if (params.parent)
  1863. {
  1864. let old = node;
  1865. node = node.closest(params.parent);
  1866. if (node === null || node.contains(scope))
  1867. {
  1868. logger('[s] went out of scope with', old);
  1869. continue;
  1870. }
  1871. }
  1872. logger('[s] processing', node);
  1873. if (toRemove.includes(node))
  1874. continue;
  1875. if (words.test(node.innerHTML))
  1876. {
  1877. // skip node if already marked for removal
  1878. logger('[s] marked for removal');
  1879. toRemove.push(node);
  1880. // add multiple nodes if defined more than one sibling
  1881. siblings = Math.abs(params.siblings) || 0;
  1882. while (siblings)
  1883. {
  1884. node = node[iterFunc];
  1885. if (!node) break; // can't go any further - exit
  1886. logger('[s] adding sibling node', node);
  1887. toRemove.push(node);
  1888. siblings -= 1;
  1889. }
  1890. }
  1891. }
  1892. let toSkip = [];
  1893. for (let node of toRemove)
  1894. if (!toRemove.every(other => other === node || !node.contains(other)))
  1895. toSkip.push(node);
  1896. if (toRemove.length)
  1897. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1898. for (let node of toRemove) if (!toSkip.includes(node))
  1899. remFunc(node);
  1900. }
  1901.  
  1902. // function to perform multiple checks if ads inserted with a delay
  1903. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1904. // also does 1 extra check when a page completely loads
  1905. // selector and words - passed dow to scissors
  1906. // params - object with multiple extra parameters:
  1907. // .log - display log in the console
  1908. // .root - selector to narrow down scope to scan;
  1909. // .observe - if true then check will be performed continuously;
  1910. // Other parameters passed down to scissors.
  1911. function gardener(selector, words, params)
  1912. {
  1913. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1914. params = params || {};
  1915. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1916. let scope;
  1917. let globalScope = [_de];
  1918. let domLoaded = false;
  1919. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1920. let onevent = e => {
  1921. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1922. for (let node of scope)
  1923. scissors(selector, words, node, params);
  1924. };
  1925. let repeater = n => {
  1926. if (!domLoaded && n) {
  1927. setTimeout(repeater, 500, n - 1);
  1928. scope = getScope(params.root);
  1929. if (!scope) // exit if the root element is not present on the page
  1930. return 0;
  1931. onevent({type: 'Repeater'});
  1932. }
  1933. };
  1934. repeater(20);
  1935. document.addEventListener(
  1936. 'DOMContentLoaded', (e) => {
  1937. domLoaded = true;
  1938. // narrow down scope to a specific element
  1939. scope = getScope(params.root);
  1940. if (!scope) // exit if the root element is not present on the page
  1941. return 0;
  1942. logger('[g] scope', scope);
  1943. // add observe mode if required
  1944. if (params.observe)
  1945. {
  1946. let params = { childList:true, subtree: true };
  1947. let observer = new MutationObserver(
  1948. function(ms)
  1949. {
  1950. for (let m of ms)
  1951. if (m.addedNodes.length)
  1952. onevent(m);
  1953. }
  1954. );
  1955. for (let node of scope)
  1956. observer.observe(node, params);
  1957. logger('[g] observer enabled');
  1958. }
  1959. onevent(e);
  1960. }, false);
  1961. // wait for a full page load to do one extra cut
  1962. win.addEventListener('load', onevent, false);
  1963. }
  1964.  
  1965. // wrap popular methods to open a new tab to catch specific behaviours
  1966. function createWindowOpenWrapper(openFunc, onClickFunc)
  1967. {
  1968. let _createElement = Document.prototype.createElement,
  1969. _appendChild = Element.prototype.appendChild,
  1970. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1971.  
  1972. let nt = new nullTools();
  1973. fakeNative(openFunc);
  1974.  
  1975. let parser = _createElement.call(document, 'a');
  1976. let openWhitelist = (url) => {
  1977. parser.href = url;
  1978. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru';
  1979. };
  1980.  
  1981. let redefineOpen = (obj) => {
  1982. for (let root of [obj, obj.document, obj.Document.prototype]) if ('open' in root) {
  1983. let _open = root.open.bind(root);
  1984. nt.define(root, 'open', (...args) => {
  1985. if (openWhitelist(args[0])) {
  1986. console.log('Whitelisted popup:', ...args);
  1987. return _open(...args);
  1988. }
  1989. return openFunc(...args);
  1990. });
  1991. }
  1992. };
  1993. redefineOpen(win);
  1994.  
  1995. function createElement(name) {
  1996. '[native code]';
  1997. // jshint validthis:true
  1998. let el = _createElement.apply(this, arguments);
  1999. // click-dispatch check for Google Chrome and similar browsers
  2000. if (el instanceof HTMLAnchorElement)
  2001. el.addEventListener('click', onClickFunc, false);
  2002. // redefine window.open in first-party frames
  2003. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  2004. el.addEventListener('load', (e) => {
  2005. try {
  2006. redefineOpen(e.target.contentWindow);
  2007. } catch(ignore) {}
  2008. }, false);
  2009. return el;
  2010. }
  2011. fakeNative(createElement);
  2012.  
  2013. let redefineCreateElement = (obj) => {
  2014. for (let root of [obj.document, obj.Document.prototype]) if ('createElement' in root)
  2015. nt.define(root, 'createElement', createElement);
  2016. };
  2017. redefineCreateElement(win);
  2018.  
  2019. // wrap window.open in newly added first-party frames
  2020. Element.prototype.appendChild = function appendChild()
  2021. {
  2022. '[native code]';
  2023. let el = _appendChild.apply(this, arguments);
  2024. if (el instanceof HTMLIFrameElement) {
  2025. try {
  2026. redefineOpen(el.contentWindow);
  2027. redefineCreateElement(el.contentWindow);
  2028. } catch(ignore) {}
  2029. }
  2030. return el;
  2031. };
  2032. fakeNative(Element.prototype.appendChild);
  2033. }
  2034.  
  2035. // Function to catch and block various methods to open a new window with 3rd-party content.
  2036. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2037. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2038. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2039. // node or simply a link with piece of javascript code in the HREF attribute.
  2040. function preventPopups()
  2041. {
  2042. // call sandbox-me if in iframe and not whitelisted
  2043. if (inIFrame) {
  2044. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2045. return;
  2046. }
  2047.  
  2048. scriptLander(() => {
  2049. let open = (...args) => {
  2050. '[native code]';
  2051. console.warn('Site attempted to open a new window', args);
  2052. if (new RegExp(`^https?://${location.hostname}/`).test(args[0])) // skip extra click in case of blocked popunder
  2053. location.assign(args[0]);
  2054. return {
  2055. document: {
  2056. write: () => {},
  2057. writeln: () => {}
  2058. }
  2059. };
  2060. };
  2061.  
  2062. let clickHandler = (e) => {
  2063. let link = e.target;
  2064. if (!link.parentNode || !e.isTrusted ||
  2065. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  2066. {
  2067. e.preventDefault();
  2068. console.warn('Blocked suspicious click event', e, 'on', e.target);
  2069. }
  2070. };
  2071.  
  2072. createWindowOpenWrapper(open, clickHandler);
  2073.  
  2074. console.log('Popup prevention enabled.');
  2075. }, nullTools, createWindowOpenWrapper);
  2076. }
  2077.  
  2078. // Helper function to close background tab if site opens itself in a new tab and then
  2079. // loads a 3rd-party page in the background one (thus performing background redirect).
  2080. function preventPopunders()
  2081. {
  2082. // create "close_me" event to call high-level window.close()
  2083. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2084. let callClose = () => (console.log('close call'), window.close());
  2085. window.addEventListener(eventName, callClose, true);
  2086.  
  2087. scriptLander(() => {
  2088. // get host of a provided URL with help of an anchor object
  2089. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2090. let parseURL = document.createElement('A');
  2091. let getHost = (url) => (parseURL.href = url, parseURL.hostname);
  2092. // site went to a new tab and attempts to unload
  2093. // call for high-level close through event
  2094. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2095. // check is URL local or goes to different site
  2096. let isLocal = (url) => {
  2097. if (url === location.pathname || url === location.href)
  2098. return true; // URL points to current pathname or full address
  2099. let host = getHost(url);
  2100. let site = location.hostname;
  2101. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2102. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2103. };
  2104.  
  2105. let _open = window.open.bind(window);
  2106. let open = (...args) => {
  2107. '[native code]';
  2108. let url = args[0];
  2109. if (url && isLocal(url))
  2110. window.addEventListener('unload', closeWindow, true);
  2111. // jshint validthis:true
  2112. return _open(...args);
  2113. };
  2114.  
  2115. let clickHandler = (e) => {
  2116. if (!e.target.parentNode || !e.isTrusted)
  2117. window.addEventListener('unload', closeWindow, true);
  2118. };
  2119.  
  2120. createWindowOpenWrapper(open, clickHandler);
  2121.  
  2122. console.log("Background redirect prevention enabled.");
  2123. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2124. }
  2125.  
  2126. // Mix between check for popups and popunders
  2127. // Significantly more agressive than both and can't be used as universal solution
  2128. function preventPopMix()
  2129. {
  2130. if (inIFrame)
  2131. {
  2132. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2133. return;
  2134. }
  2135.  
  2136. // create "close_me" event to call high-level window.close()
  2137. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2138. let callClose = () => (console.log('close call'), window.close());
  2139. window.addEventListener(eventName, callClose, true);
  2140.  
  2141. scriptLander(() => {
  2142. let _open = window.open,
  2143. parseURL = document.createElement('A');
  2144. // get host of a provided URL with help of an anchor object
  2145. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2146. let getHost = (url) => (parseURL.href = url, parseURL.host);
  2147. // site went to a new tab and attempts to unload
  2148. // call for high-level close through event
  2149. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  2150. // check is URL local or goes to different site
  2151. function isLocal(url)
  2152. {
  2153. let loc = window.location;
  2154. if (url === loc.pathname || url === loc.href)
  2155. return true; // URL points to current pathname or full address
  2156. let host = getHost(url),
  2157. site = loc.host;
  2158. if (host === '')
  2159. return false; // URLs with unusual protocol may have empty 'host'
  2160. if (host.length > site.length)
  2161. [site, host] = [host, site];
  2162. return site.includes(host, site.length - host.length);
  2163. }
  2164.  
  2165. // add check for redirect for 5 seconds, then disable it
  2166. function checkRedirect()
  2167. {
  2168. window.addEventListener('unload', closeWindow, true);
  2169. setTimeout(closeWindow=>window.removeEventListener('unload', closeWindow, true), 5000, closeWindow);
  2170. }
  2171.  
  2172. function open(url, name)
  2173. {
  2174. '[native code]';
  2175. if (url && isLocal(url) && (!name || name === '_blank'))
  2176. {
  2177. console.warn('Suspicious local new window', arguments);
  2178. checkRedirect();
  2179. // jshint validthis:true
  2180. return _open.apply(this, arguments);
  2181. }
  2182. console.warn('Blocked attempt to open a new window', arguments);
  2183. return {
  2184. document: {
  2185. write: () => {},
  2186. writeln: () => {}
  2187. }
  2188. };
  2189. }
  2190.  
  2191. function clickHandler(e)
  2192. {
  2193. let link = e.target,
  2194. url = link.href||'';
  2195. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  2196. {
  2197. console.log('Link', link, 'were created dinamically, but looks fine.');
  2198. return true;
  2199. }
  2200. if (isLocal(url) && link.target === '_blank')
  2201. {
  2202. console.log('Suspicious local link', link);
  2203. checkRedirect();
  2204. return;
  2205. }
  2206. console.log('Blocked suspicious click on a link', link);
  2207. e.stopPropagation();
  2208. e.preventDefault();
  2209. }
  2210.  
  2211. createWindowOpenWrapper(open, clickHandler);
  2212.  
  2213. console.log("Mixed popups prevention enabled.");
  2214. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2215. }
  2216. // External listener for case when site known to open popups were loaded in iframe
  2217. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2218. // Some sites replace frame's window.location with data-url to run in clean context
  2219. if (!inIFrame)
  2220. {
  2221. window.addEventListener(
  2222. 'message', function(e)
  2223. {
  2224. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2225. return;
  2226. let src = e.data.href;
  2227. for (let frame of document.querySelectorAll('iframe'))
  2228. if (frame.contentWindow === e.source)
  2229. {
  2230. if (frame.hasAttribute('sandbox'))
  2231. {
  2232. if (!frame.sandbox.contains('allow-popups'))
  2233. return; // exit frame since it's already sandboxed and popups are blocked
  2234. // remove allow-popups if frame already sandboxed
  2235. frame.sandbox.remove('allow-popups');
  2236. } else {
  2237. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2238. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2239. // but to apply content must be reloaded and this script will re-apply it in the result
  2240. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2241. }
  2242. console.log('Disallowed popups from iframe', frame);
  2243.  
  2244. // reload frame content to apply restrictions
  2245. if (!src) {
  2246. src = frame.src;
  2247. console.log('Unable to get current iframe location, reloading from src', src);
  2248. } else
  2249. console.log('Reloading iframe with URL', src);
  2250. frame.src = 'about:blank';
  2251. frame.src = src;
  2252. }
  2253. }, false
  2254. );
  2255. }
  2256.  
  2257. function selectiveEval() {
  2258. scriptLander(() => {
  2259. let nt = new nullTools();
  2260. let _eval = win.eval.bind(window);
  2261. nt.define(win, 'eval', function(...args) {
  2262. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  2263. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2264. return null;
  2265. }
  2266. return _eval(...args);
  2267. });
  2268. }, nullTools);
  2269. }
  2270.  
  2271. // === Scripts for specific domains ===
  2272.  
  2273. let scripts = {};
  2274. // prevent popups and redirects block
  2275. // Popups
  2276. scripts.preventPopups = {
  2277. other: [
  2278. 'biqle.ru',
  2279. 'chaturbate.com',
  2280. 'dfiles.ru',
  2281. 'hentaiz.org',
  2282. 'mirrorcreator.com',
  2283. 'online-multy.ru',
  2284. 'radikal.ru', 'rumedia.ws',
  2285. 'seedoff.cc', 'seedoff.tv',
  2286. 'thepiratebay.org', 'torseed.net',
  2287. 'unionpeer.com',
  2288. 'zippyshare.com'
  2289. ],
  2290. now: preventPopups
  2291. };
  2292. // Popunders (background redirect)
  2293. scripts.preventPopunders = {
  2294. other: [
  2295. 'lostfilm-online.ru',
  2296. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2297. 'perfectgirls.net'
  2298. ],
  2299. now: preventPopunders
  2300. };
  2301. // PopMix (both types of popups encountered on site)
  2302. scripts['openload.co'] = {
  2303. other: ['oload.tv', 'oload.info'],
  2304. now: () => {
  2305. let nt = new nullTools();
  2306. nt.define(win, 'CNight', win.CoinHive);
  2307. if (location.pathname.startsWith('/embed/'))
  2308. {
  2309. nt.define(win, 'BetterJsPop', {
  2310. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2311. config: ((o) => console.warn('BetterJsPop.config', o)),
  2312. Browser: { isChrome: true }
  2313. });
  2314. nt.define(win, 'isSandboxed', nt.func(null));
  2315. nt.define(win, 'adblock', false);
  2316. nt.define(win, 'adblock2', false);
  2317. } else
  2318. preventPopMix();
  2319. }
  2320. };
  2321. scripts['turbobit.net'] = preventPopMix;
  2322.  
  2323. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2324. scripts['tapochek.net'] = () => {
  2325. let _appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  2326. let _appendChild_value = _appendChild.value;
  2327. _appendChild.value = function appendChild(node) {
  2328. if (this === win.document.body)
  2329. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2330. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2331. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2332. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2333. throw '...eenope!';
  2334. return _appendChild_value.apply(this, arguments);
  2335. };
  2336. Object.defineProperty(Node.prototype, 'appendChild', _appendChild);
  2337.  
  2338. preventPopups();
  2339. };
  2340.  
  2341. scripts['rustorka.com'] = {
  2342. other: ['rustorka.lib'],
  2343. dom: () => scriptLander(() => {
  2344. let link = void 0;
  2345. document.body.addEventListener('mousedown', e => {
  2346. link = e.target.closest('a, select');
  2347. }, false);
  2348. let _open = window.open.bind(window);
  2349. let _getAttribute = Element.prototype.getAttribute;
  2350. win.open = (...args) => {
  2351. let url = args[0];
  2352. let allow = false;
  2353. if (link instanceof HTMLAnchorElement) {
  2354. // third-party post links
  2355. let href = _getAttribute.call(link, 'href');
  2356. if (link.classList.contains('postLink') &&
  2357. !link.matches(`a[href*="${location.hostname}"]`) &&
  2358. (href === url || link.href === url)) {
  2359. return _open(...args);
  2360. }
  2361. // onclick # links
  2362. if (href === '#' && /window\.open/.test(_getAttribute.call(link, 'onclick'))) {
  2363. return _open(...args);
  2364. }
  2365. // force local links to load in the current window
  2366. if (href.includes(`//${location.hostname}/`))
  2367. location.assign(href);
  2368. }
  2369. // list of image hostings under upload picture button (new comment)
  2370. if (link instanceof HTMLSelectElement &&
  2371. !url.includes(location.hostname) &&
  2372. link.value === url) {
  2373. return _open(...args);
  2374. }
  2375. // looks like tabunder
  2376. if (link === null && url === location.href)
  2377. location.replace(url); // reload current page
  2378. // other cases
  2379. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2380. return {};
  2381. };
  2382. })
  2383. };
  2384.  
  2385. // other
  2386. scripts['1tv.ru'] = () => scriptLander(() => {
  2387. let nt = new nullTools();
  2388. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2389. let _EUMPConfig = void 0;
  2390. let disablePlugins = {
  2391. 'antiblock': false,
  2392. 'stat1tv': false
  2393. };
  2394. Object.defineProperty(win, 'EUMPConfig', {
  2395. enumerable: true,
  2396. get: x => _EUMPConfig,
  2397. set: x => {
  2398. let plugins = x.plugins;
  2399. if (plugins) {
  2400. let id;
  2401. for (let plugin in disablePlugins) {
  2402. id = plugins.indexOf(plugin);
  2403. if (id > -1) {
  2404. plugins.splice(id, 1);
  2405. disablePlugins[plugin] = true;
  2406. }
  2407. }
  2408. console.warn(`Player plugins: active [${plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2409. }
  2410. _EUMPConfig = x;
  2411. }
  2412. });
  2413. }, nullTools);
  2414.  
  2415. scripts['2picsun.ru'] = {
  2416. other: [
  2417. 'pics2sun.ru', '3pics-img.ru'
  2418. ],
  2419. now: () => {
  2420. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2421. }
  2422. };
  2423.  
  2424. scripts['4pda.ru'] = {
  2425. now: () => {
  2426. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2427. let hStyle,
  2428. isForum = document.location.href.search('/forum/') !== -1,
  2429. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2430. afterClean = () => remove(hStyle);
  2431.  
  2432. function beforeClean()
  2433. {
  2434. // attach styles before document displayed
  2435. hStyle = createStyle([
  2436. 'html { overflow-y: scroll }',
  2437. 'article + aside * { display: none !important }',
  2438. `section[id] {${(
  2439. 'position: absolute;'+
  2440. 'width: 100%'
  2441. )}}`,
  2442. `#header + div:after {${(
  2443. 'content: "";'+
  2444. 'position: fixed;'+
  2445. 'top: 0;'+
  2446. 'left: 0;'+
  2447. 'width: 100%;'+
  2448. 'height: 100%;'+
  2449. 'background-color: #E6E7E9'
  2450. )}}`,
  2451. // http://codepen.io/Beaugust/pen/DByiE
  2452. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2453. `article + aside:after {${(
  2454. 'content: "";'+
  2455. 'position: absolute;'+
  2456. 'width: 150px;'+
  2457. 'height: 150px;'+
  2458. 'top: 150px;'+
  2459. 'left: 50%;'+
  2460. 'margin-top: -75px;'+
  2461. 'margin-left: -75px;'+
  2462. 'box-sizing: border-box;'+
  2463. 'border-radius: 100%;'+
  2464. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2465. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2466. 'animation: spin 2s infinite linear'
  2467. )}}`
  2468. ], {id:'ubrHider'}, true);
  2469.  
  2470. // display content of a page if time to load a page is more than 2 seconds to avoid
  2471. // blocking access to a page if it is loading for too long or stuck in a loading state
  2472. setTimeout(2000, afterClean);
  2473. }
  2474.  
  2475. createStyle([
  2476. '#nav .use-ad { display: block !important }',
  2477. 'article:not(.post) + article:not(#id),'+
  2478. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2479. ]);
  2480.  
  2481. if (!isForum)
  2482. beforeClean();
  2483.  
  2484. // save links to non-overridden functions to use later
  2485. let protectedElems;
  2486. // protect/hide changed attributes in case site attempt to restore them
  2487. function styleProtector(eventMode)
  2488. {
  2489. let _toLowerCase = String.prototype.toLowerCase,
  2490. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2491. protectedElems = new WeakMap();
  2492. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2493. {
  2494. let originalFunction = element.prototype[functionName];
  2495. element.prototype[functionName] = function wrapper()
  2496. {
  2497. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2498. return returnIfProtected(this, arguments);
  2499. return originalFunction.apply(this, arguments);
  2500. };
  2501. }
  2502. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2503. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2504. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2505. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2506. if (!eventMode)
  2507. return protectedElems;
  2508. else
  2509. {
  2510. let e = document.createEvent('Event');
  2511. e.initEvent('protoOverride', false, false);
  2512. window.protectedElems = protectedElems;
  2513. window.dispatchEvent(e);
  2514. }
  2515. }
  2516. if (!isFirefox)
  2517. protectedElems = styleProtector(false);
  2518. else
  2519. {
  2520. let script = document.createElement('script');
  2521. script.textContent = `(${styleProtector.toString()})(true);`;
  2522. window.addEventListener(
  2523. 'protoOverride', function protoOverrideCallback(e)
  2524. {
  2525. if (win.protectedElems) {
  2526. protectedElems = win.protectedElems;
  2527. delete win.protectedElems;
  2528. }
  2529. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2530. }, true
  2531. );
  2532. _appendChild(script);
  2533. _removeChild(script);
  2534. }
  2535.  
  2536. // clean a page
  2537. window.addEventListener(
  2538. 'DOMContentLoaded', function()
  2539. {
  2540. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2541. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2542.  
  2543. if (isForum)
  2544. {
  2545. let si = document.querySelector('#logostrip');
  2546. if (si)
  2547. remove(si.parentNode.nextSibling);
  2548. }
  2549.  
  2550. if (document.location.href.search('/forum/dl/') !== -1) {
  2551. let setBackground = node => _setAttribute.call(
  2552. node,
  2553. 'style', (_getAttribute.call(node, 'style') || '') +
  2554. ';background-color:#4ebaf6!important'
  2555. );
  2556. setBackground(document.body);
  2557. for (let itm of document.querySelectorAll('body>div, body>div>div'))
  2558. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer')) {
  2559. remove(itm);
  2560. } else {
  2561. setBackground(itm);
  2562. }
  2563. }
  2564.  
  2565. if (isForum) // Do not continue if it's a forum
  2566. return;
  2567.  
  2568. {
  2569. let si = document.querySelector('#header');
  2570. if (si)
  2571. {
  2572. let rem = si.previousSibling;
  2573. while (rem)
  2574. {
  2575. si = rem.previousSibling;
  2576. remove(rem);
  2577. rem = si;
  2578. }
  2579. }
  2580. }
  2581.  
  2582. for (let itm of document.querySelectorAll('#nav li[class]'))
  2583. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2584. remove(itm);
  2585.  
  2586. let style, result,
  2587. fakeStyles = new WeakMap(),
  2588. styleProxy = {
  2589. get: function(target, prop)
  2590. {
  2591. let fakeStyle = fakeStyles.get(target);
  2592. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2593. },
  2594. set: function(target, prop, value)
  2595. {
  2596. let fakeStyle = fakeStyles.get(target);
  2597. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2598. return true;
  2599. }
  2600. };
  2601. for (let itm of document.querySelectorAll('DIV, A'))
  2602. {
  2603. if (itm.tagName ==='DIV' &&
  2604. itm.offsetWidth > 0.95 * width() &&
  2605. itm.offsetHeight > 0.85 * height())
  2606. {
  2607. style = window.getComputedStyle(itm, null);
  2608. result = [];
  2609.  
  2610. if (style.backgroundImage !== 'none')
  2611. result.push('background-image:none!important');
  2612.  
  2613. if (style.backgroundColor !== 'transparent' &&
  2614. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2615. result.push('background-color:transparent!important');
  2616.  
  2617. if (result.length)
  2618. {
  2619. if (itm.getAttribute('style'))
  2620. result.unshift(itm.getAttribute('style'));
  2621.  
  2622. fakeStyles.set(itm.style, {
  2623. 'backgroundImage': itm.style.backgroundImage,
  2624. 'backgroundColor': itm.style.backgroundColor
  2625. });
  2626.  
  2627. try {
  2628. Object.defineProperty(itm, 'style', {
  2629. value: new Proxy(itm.style, styleProxy),
  2630. enumerable: true
  2631. });
  2632. } catch (e) {
  2633. console.log('Unable to protect style property.', e);
  2634. }
  2635.  
  2636. if (protectedElems)
  2637. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2638.  
  2639. _setAttribute.call(itm, 'style', result.join(';'));
  2640. }
  2641. }
  2642. if (itm.tagName ==='A' &&
  2643. (itm.offsetWidth > 0.95 * width() ||
  2644. itm.offsetHeight > 0.85 * height()))
  2645. {
  2646. if (protectedElems)
  2647. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2648.  
  2649. _setAttribute.call(itm, 'style', 'display:none!important');
  2650. }
  2651. }
  2652.  
  2653. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2654. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2655. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2656. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2657. remove(itm);
  2658.  
  2659. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2660.  
  2661. // display content of the page
  2662. afterClean();
  2663. }
  2664. );
  2665. }
  2666. };
  2667.  
  2668. scripts['adhands.ru'] = () => scriptLander(() => {
  2669. let nt = new nullTools();
  2670. try {
  2671. let _adv;
  2672. Object.defineProperty(win, 'adv', {
  2673. get: () => _adv,
  2674. set: (v) => {
  2675. console.log('Blocked advert on adhands.ru.');
  2676. nt.define(v, 'advert', '');
  2677. _adv = v;
  2678. }
  2679. });
  2680. } catch (ignore) {
  2681. if (!win.adv)
  2682. console.log('Unable to locate advert on adhands.ru.');
  2683. else {
  2684. console.log('Blocked advert on adhands.ru.');
  2685. nt.define(win.adv, 'advert', '');
  2686. }
  2687. }
  2688. }, nullTools);
  2689.  
  2690. scripts['allhentai.ru'] = () => {
  2691. selectiveEval();
  2692. preventPopups();
  2693. scriptLander(() => {
  2694. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2695. if (!_onerror)
  2696. return;
  2697. _onerror.set = (...args) => console.log(args[0].toString());
  2698. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2699. });
  2700. };
  2701.  
  2702. scripts['allmovie.pro'] = {
  2703. other: ['rufilmtv.org'],
  2704. dom: function()
  2705. {
  2706. // pretend to be Android to make site use different played for ads
  2707. if (isSafari)
  2708. return;
  2709. Object.defineProperty(navigator, 'userAgent', {
  2710. get: function(){ 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'; },
  2711. enumerable: true
  2712. });
  2713. }
  2714. };
  2715.  
  2716. scripts['anidub-online.ru'] = {
  2717. other: ['online.anidub.com'],
  2718. dom: function()
  2719. {
  2720. if (win.ogonekstart1)
  2721. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2722. },
  2723. now: () => createStyle([
  2724. '.background {background: none!important;}',
  2725. '.background > script + div,'+
  2726. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2727. '{display:none!important}'
  2728. ])
  2729. };
  2730.  
  2731. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2732.  
  2733. scripts['fishki.net'] = () => {
  2734. scriptLander(() => {
  2735. let nt = new nullTools();
  2736. let fishki = {};
  2737. nt.define(fishki, 'adv', nt.proxy({
  2738. afterAdblockCheck: nt.func(null),
  2739. refreshFloat: nt.func(null)
  2740. }));
  2741. nt.define(fishki, 'is_adblock', false);
  2742. nt.define(win, 'fishki', fishki);
  2743. }, nullTools);
  2744. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2745. };
  2746.  
  2747. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2748.  
  2749. scripts['hdgo.cc'] = {
  2750. other: ['46.30.43.38', 'couber.be'],
  2751. now: () => (new MutationObserver(
  2752. (ms) => {
  2753. let m, node;
  2754. for (m of ms) for (node of m.addedNodes)
  2755. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2756. node.removeAttribute('onerror');
  2757. }
  2758. )).observe(document.documentElement, { childList:true, subtree: true })
  2759. };
  2760.  
  2761. scripts['gismeteo.ru'] = {
  2762. other: ['gismeteo.ua'],
  2763. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2764. };
  2765.  
  2766. scripts['hdrezka.ag'] = () => {
  2767. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2768. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2769. };
  2770.  
  2771. scripts['hideip.me'] = {
  2772. now: () => scriptLander(() => {
  2773. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2774. let _set_innerHTML = _innerHTML.set;
  2775. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2776. let _get_innerText = _innerText.get;
  2777. let div = document.createElement('div');
  2778. _innerHTML.set = function(...args) {
  2779. _set_innerHTML.call(div, args[0].replace('i','a'));
  2780. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2781. /(\d\d\d?\.){3}\d\d\d?\:\d/.test(_get_innerText.call(this)) ) {
  2782. console.log('Anti-Adblock killed.');
  2783. return true;
  2784. }
  2785. _set_innerHTML.apply(this, args);
  2786. };
  2787. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2788. Object.defineProperty(win, 'adblock', {
  2789. get: x => false,
  2790. set: x => null,
  2791. enumerable: true
  2792. });
  2793. let _$ = {};
  2794. let _$_map = new WeakMap();
  2795. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2796. let _val_gOPD = _gOPD.value;
  2797. _gOPD.value = function(...args) {
  2798. let _res = _val_gOPD.apply(this, args);
  2799. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2800. delete _res.get;
  2801. delete _res.set;
  2802. _res.value = win[args[1]];
  2803. }
  2804. return _res;
  2805. };
  2806. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2807. let getJQWrap = (n) => {
  2808. let name = n;
  2809. return {
  2810. enumerable: true,
  2811. get: x => _$[name],
  2812. set: x => {
  2813. if (_$_map.has(x)) {
  2814. _$[name] = _$_map.get(x);
  2815. return true;
  2816. }
  2817. if (x === _$.$ || x === _$.jQuery) {
  2818. _$[name] = x;
  2819. return true;
  2820. }
  2821. _$[name] = new Proxy(x, {
  2822. apply: (t, o, args) => {
  2823. let _res = t.apply(o, args);
  2824. if (_$_map.has(_res.is)) {
  2825. _res.is = _$_map.get(_res.is);
  2826. } else {
  2827. let _is = _res.is;
  2828. _res.is = function(...args) {
  2829. if (args[0] === ':hidden')
  2830. return false;
  2831. return _is.apply(this, args);
  2832. };
  2833. _$_map.set(_is, _res.is);
  2834. }
  2835. return _res;
  2836. }
  2837. });
  2838. _$_map.set(x, _$[name]);
  2839. return true;
  2840. }
  2841. };
  2842. };
  2843. Object.defineProperty(win, '$', getJQWrap('$'));
  2844. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2845. let _dP = Object.defineProperty;
  2846. Object.defineProperty = function(...args) {
  2847. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2848. return void 0;
  2849. return _dP.apply(this, args);
  2850. };
  2851. })
  2852. };
  2853.  
  2854. scripts['imageban.ru'] = {
  2855. now: preventPopunders,
  2856. dom: () => win.addEventListener('unload', () => location.hash = 'x'+Math.random().toString(36).substr(2), true)
  2857. };
  2858.  
  2859. scripts['kinopoisk.ru'] = {
  2860. now: () => {
  2861. // set no-branding body style
  2862. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2863. },
  2864. dom: () => {
  2865. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  2866. )(_de.querySelector('#branding-style'));
  2867. }
  2868. };
  2869.  
  2870. scripts['mail.ru'] = () => scriptLander(() => {
  2871. let nt = new nullTools();
  2872. // Trick to prevent mail.ru from removing 3rd-party styles
  2873. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2874. // Disable some of their counters
  2875. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2876. if (location.hostname !== 'e.mail.ru')
  2877. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2878. else
  2879. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2880.  
  2881. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2882. function defineLocator(root)
  2883. {
  2884. let _locator;
  2885. let fishnet = {
  2886. apply: (target, thisArg, args) => {
  2887. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2888. return target.apply(thisArg, args);
  2889. }
  2890. };
  2891.  
  2892. function wrapLocator(locator)
  2893. {
  2894. if ('setup' in locator)
  2895. {
  2896. let _setup = locator.setup;
  2897. locator.setup = function(o)
  2898. {
  2899. if ('enable' in o)
  2900. {
  2901. o.enable = false;
  2902. console.log('Disable mimic mode.');
  2903. }
  2904. if ('links' in o)
  2905. {
  2906. o.links = [];
  2907. console.log('Call with empty list of sheets.');
  2908. }
  2909. return _setup.call(this, o);
  2910. };
  2911. locator.insertSheet = () => console.log('Ignore insertSheet.');
  2912. locator.wrap = () => console.log('Ignore wrap.');
  2913. }
  2914. try {
  2915. let names = [];
  2916. for (let name in locator)
  2917. if (locator[name] instanceof Function) {
  2918. locator[name]._name = name;
  2919. locator[name] = new Proxy(locator[name], fishnet);
  2920. names.push(name);
  2921. }
  2922. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  2923. } catch(e) {
  2924. console.log(e);
  2925. }
  2926. _locator = locator;
  2927. }
  2928.  
  2929. if ('locator' in root && root.locator)
  2930. {
  2931. console.log('Found existing "locator" object. :|');
  2932. _locator = root.locator;
  2933. wrapLocator(root.locator);
  2934. }
  2935.  
  2936. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  2937. if (!loc_desc || loc_desc.set !== wrapLocator)
  2938. try {
  2939. Object.defineProperty(root, 'locator', {
  2940. set: wrapLocator,
  2941. get: () => _locator
  2942. });
  2943. } catch (err) {
  2944. console.log('Unable to redefine "locator" object!!!', err);
  2945. }
  2946. }
  2947.  
  2948. function defineDetector(mr)
  2949. {
  2950. let __ = mr._ || {};
  2951.  
  2952. if ('HONEYPOT' in __)
  2953. {
  2954. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  2955. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  2956. nt.define(__, 'STUCK_IN_POT', false);
  2957. }
  2958.  
  2959. __ = new Proxy(__, {
  2960. get: (t, p) => t[p],
  2961. set: (t, p, v) => {
  2962. console.log(`mr._.${p} =`, v);
  2963. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  2964. console.log('Not changed.');
  2965. t[p] = v; // setter in nt.define will prevent this when needed
  2966. return true;
  2967. }
  2968. });
  2969. Object.defineProperty(mr, '_', {
  2970. enumerable: true,
  2971. value: __
  2972. });
  2973. }
  2974.  
  2975. if (location.hostname === 'e.mail.ru')
  2976. defineLocator(win);
  2977. else {
  2978. try {
  2979. let _mr;
  2980. Object.defineProperty(win, 'mr', {
  2981. enumerable: true,
  2982. get: () => _mr,
  2983. set: (v) => {
  2984. if (v === _mr)
  2985. return true;
  2986. console.log('Trapped new "mr" object.');
  2987. defineLocator(v.mimic ? v.mimic : v);
  2988. defineDetector(v);
  2989. _mr = v;
  2990. }
  2991. });
  2992. if (!('mr' in win))
  2993. throw 'Wat!?';
  2994. } catch (e) {
  2995. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  2996. defineLocator(win.mr);
  2997. defineDetector(win.mr);
  2998. }
  2999. }
  3000. }, nullTools);
  3001.  
  3002. scripts['megogo.net'] = {
  3003. now: () => {
  3004. let nt = new nullTools();
  3005. nt.define(win, 'adBlock', false);
  3006. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3007. }
  3008. };
  3009.  
  3010. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3011.  
  3012. scripts['overclockers.ru'] = {
  3013. now: () => scriptLander(() => {
  3014. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  3015. let _set_innerHTML = _innerHTML.set;
  3016. _innerHTML.set = function() {
  3017. if (this === document.body) {
  3018. console.log('Anti-Adblock killed.');
  3019. return true;
  3020. }
  3021. _set_innerHTML.apply(this, arguments);
  3022. };
  3023. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  3024. })
  3025. };
  3026. scripts['forums.overclockers.ru'] = {
  3027. now: () => {
  3028. createStyle('.needblock {position: fixed; left: -10000px}');
  3029. Object.defineProperty(win, 'adblck', {
  3030. get: () => 'no',
  3031. set: () => undefined,
  3032. enumerable: true
  3033. });
  3034. }
  3035. };
  3036.  
  3037. scripts['pb.wtf'] = {
  3038. other: ['piratbit.org', 'piratbit.ru'],
  3039. now: () => {
  3040. // line above topic content and images in the slider in the header
  3041. gardener(
  3042. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  3043. /img|Реклама|center/i,
  3044. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  3045. );
  3046. // ads in comments
  3047. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  3048. }
  3049. };
  3050.  
  3051. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3052.  
  3053. scripts['peka2.tv'] = () => {
  3054. let bodyClass = 'body--branding';
  3055. let checkNode = node => {
  3056. for (let className of node.classList)
  3057. if (className.includes('banner') || className === bodyClass) {
  3058. _removeAttribute.call(node, 'style');
  3059. node.classList.remove(className);
  3060. for (let attr of Array.from(node.attributes)) {
  3061. if (attr.name.startsWith('advert'))
  3062. _removeAttribute.call(node, attr.name);
  3063. }
  3064. }
  3065. };
  3066. (new MutationObserver(ms => {
  3067. let m, node;
  3068. for (m of ms) for (node of m.addedNodes)
  3069. if (node instanceof HTMLElement)
  3070. checkNode(node);
  3071. })).observe(_de, {childList: true, subtree: true});
  3072. (new MutationObserver(ms => {
  3073. for (let m of ms)
  3074. checkNode(m.target);
  3075. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3076. };
  3077.  
  3078. scripts['qrz.ru'] = {
  3079. now: () => {
  3080. let nt = new nullTools();
  3081. nt.define(win, 'ab', false);
  3082. nt.define(win, 'tryMessage', nt.func(null));
  3083. }
  3084. };
  3085.  
  3086. scripts['razlozhi.ru'] = {
  3087. now: () => {
  3088. for (let func of ['createShadowRoot', 'attachShadow'])
  3089. if (func in Element.prototype)
  3090. Element.prototype[func] = function(){ return this.cloneNode(); };
  3091. }
  3092. };
  3093.  
  3094. scripts['rbc.ru'] = {
  3095. dom: () => {
  3096. let _preventDefault = Event.prototype.preventDefault;
  3097. Event.prototype.preventDefault = function preventDefault()
  3098. {
  3099. let t = this.target;
  3100. if (t instanceof HTMLAnchorElement || t.closest('A'))
  3101. throw new Error('an.yandex redirect prevention');
  3102. return _preventDefault.call(this);
  3103. };
  3104.  
  3105. function cleaner(nodes)
  3106. {
  3107. for (let node of nodes)
  3108. {
  3109. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  3110. continue;
  3111. node.classList.remove('js-yandex-counter');
  3112. node.removeAttribute('data-yandex-name');
  3113. node.removeAttribute('data-yandex-params');
  3114. }
  3115. }
  3116. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  3117.  
  3118. (new MutationObserver(
  3119. ms => { for (let m of ms) cleaner(m.addedNodes); }
  3120. )).observe(_de, {childList: true, subtree: true});
  3121. }
  3122. };
  3123.  
  3124. scripts['rp5.ru'] = {
  3125. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3126. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3127. };
  3128.  
  3129. scripts['spaces.ru'] = () => {
  3130. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3131. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3132. };
  3133.  
  3134. scripts['spam-club.blogspot.co.uk'] = () => {
  3135. let _clientHeight = Object.getOwnPropertyDescriptor(Element.prototype, 'clientHeight'),
  3136. _clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth');
  3137. let wrapGetter = (getter) => {
  3138. let _getter = getter;
  3139. return function()
  3140. {
  3141. let _size = _getter.apply(this, arguments);
  3142. return _size ? _size : 1;
  3143. };
  3144. };
  3145. _clientHeight.get = wrapGetter(_clientHeight.get);
  3146. _clientWidth.get = wrapGetter(_clientWidth.get);
  3147. Object.defineProperty(Element.prototype, 'clientHeight', _clientHeight);
  3148. Object.defineProperty(Element.prototype, 'clientWidth', _clientWidth);
  3149. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3150. _set_onload = _onload.set;
  3151. _onload.set = function()
  3152. {
  3153. if (this instanceof HTMLImageElement)
  3154. return true;
  3155. _set_onload.apply(this, arguments);
  3156. };
  3157. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3158. };
  3159.  
  3160. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3161.  
  3162. scripts['sports.ru'] = {
  3163. now: () => {
  3164. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3165. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3166. // extra functionality: shows/hides panel at the top depending on scroll direction
  3167. createStyle([
  3168. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3169. '.user-panel-up { top: -40px!important }'
  3170. ], {id: 'userPanelSlide'}, false);
  3171. },
  3172. dom: () => {
  3173. (function lookForPanel()
  3174. {
  3175. let panel = document.querySelector('.user-panel__fixed');
  3176. if (!panel)
  3177. setTimeout(lookForPanel, 100);
  3178. else
  3179. window.addEventListener(
  3180. 'wheel', function(e)
  3181. {
  3182. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3183. panel.classList.add('user-panel-up');
  3184. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3185. panel.classList.remove('user-panel-up');
  3186. }, false
  3187. );
  3188. })();
  3189. }
  3190. };
  3191.  
  3192. scripts['vk.com'] = () => gardener((
  3193. '#wk_content > #wl_post > div,'+
  3194. '#page_wall_posts > div[id^="post-"],'+
  3195. 'div[class^="feed_row "] > div[id^="post-"],'+
  3196. 'div[class^="feed_row "] > div[id^="feed_repost-"]'
  3197. ), /wall_marked_as_ads/, {root: 'body', observe: true});
  3198.  
  3199. scripts['yap.ru'] = {
  3200. other: ['yaplakal.com'],
  3201. now: () => {
  3202. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3203. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3204. }
  3205. };
  3206.  
  3207. scripts['rambler.ru'] = {
  3208. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru', 'quto.ru'],
  3209. now: () => scriptLander(() => {
  3210. // Prevent autoplay
  3211. if (!('EaglePlayer' in win)) {
  3212. let _EaglePlayer = void 0;
  3213. Object.defineProperty(win, 'EaglePlayer', {
  3214. enumerable: true,
  3215. get: x => _EaglePlayer,
  3216. set: x => {
  3217. if (x === _EaglePlayer)
  3218. return true;
  3219. _EaglePlayer = x;
  3220. let _init = void 0;
  3221. Object.defineProperty(_EaglePlayer.prototype, 'init', {
  3222. enumerable: true,
  3223. set: x => _init = x,
  3224. get: function() {
  3225. let _self = this;
  3226. if (_self.options) {
  3227. Object.defineProperty(this.options, 'autoplay', {
  3228. enumerable: true,
  3229. get: x => false,
  3230. set: x => null
  3231. });
  3232. }
  3233. if (_self.options && _self.options.el && inIFrame) {
  3234. let addListener = (player) => {
  3235. console.log('Attached autostop');
  3236. player.addEventListener('canplay', e => {
  3237. e.target.play = () => console.log('Applied autostop.');
  3238. setTimeout(player => {
  3239. delete player.play;
  3240. console.log('Detached autostop');
  3241. }, 1500, e.target);
  3242. }, false);
  3243. };
  3244. (new MutationObserver(ms => {
  3245. let m, node;
  3246. for (m of ms) for (node of m.addedNodes)
  3247. if (node instanceof HTMLVideoElement)
  3248. addListener(node);
  3249. })).observe(this.options.el, { childList: true, subtree: true });
  3250. }
  3251. return _init;
  3252. }
  3253. });
  3254. }
  3255. });
  3256. let _setAttribute = Element.prototype.setAttribute;
  3257. let isAutoplay = /^autoplay$/i;
  3258. Element.prototype.setAttribute = function setAttribute(name)
  3259. {
  3260. if (!this._stopped && isAutoplay.test(name))
  3261. {
  3262. console.log('Prevented assigning autoplay attribute.');
  3263. return null;
  3264. }
  3265. return _setAttribute.apply(this, arguments);
  3266. };
  3267. } else if (inIFrame) {
  3268. let _setAttribute = Element.prototype.setAttribute;
  3269. let isAutoplay = /^autoplay$/i;
  3270. Element.prototype.setAttribute = function setAttribute(name)
  3271. {
  3272. if (!this._stopped && isAutoplay.test(name))
  3273. {
  3274. console.log('Prevented assigning autoplay attribute.');
  3275. this._stopped = true;
  3276. this.play = () => {
  3277. console.log('Prevented attempt to force-start playback.');
  3278. delete this.play;
  3279. };
  3280. return null;
  3281. }
  3282. return _setAttribute.apply(this, arguments);
  3283. };
  3284. }
  3285. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3286. return;
  3287. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3288. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3289. let _cssText_get = _cssText.get;
  3290. _cssText.configurable = false;
  3291. _cssText.get = function()
  3292. {
  3293. let cssText = _cssText_get.call(this);
  3294. if (cssText.includes('content:'))
  3295. {
  3296. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3297. return null;
  3298. }
  3299. return cssText;
  3300. };
  3301. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3302. // fake global Adf object
  3303. let nt = new nullTools();
  3304. let ssPromise = nt.func(new Promise((r,j) => r({status: true})));
  3305. nt.define(win, 'Adf', nt.proxy({
  3306. banner: nt.proxy({
  3307. sspScroll: ssPromise,
  3308. ssp: ssPromise
  3309. })
  3310. }));
  3311. // extra script to remove partner news on gazeta.ru
  3312. if (!location.hostname.includes('gazeta.ru'))
  3313. return;
  3314. (new MutationObserver(
  3315. (ms) => {
  3316. let m, node, header;
  3317. for (m of ms) for (node of m.addedNodes)
  3318. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  3319. {
  3320. header = node.querySelector('.sausage-header');
  3321. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3322. node.style.display = 'none';
  3323. }
  3324. }
  3325. )).observe(document.documentElement, { childList:true, subtree: true });
  3326. }, `let inIFrame = ${inIFrame}`, nullTools)
  3327. };
  3328.  
  3329. scripts['reactor.cc'] = {
  3330. other: ['joyreactor.cc', 'pornreactor.cc'],
  3331. now: () => {
  3332. selectiveEval();
  3333. scriptLander(() => {
  3334. let nt = new nullTools();
  3335. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  3336. nt.define(win, 'Worker', function(){});
  3337. nt.define(win, 'JRCH', win.CoinHive);
  3338. }, nullTools);
  3339. },
  3340. click: function(e)
  3341. {
  3342. let node = e.target;
  3343. if (node.nodeType === Node.ELEMENT_NODE &&
  3344. node.style.position === 'absolute' &&
  3345. node.style.zIndex > 0)
  3346. node.parentNode.removeChild(node);
  3347. },
  3348. dom: function()
  3349. {
  3350. let words = new RegExp(
  3351. 'блокировщик рекламы'
  3352. .split('')
  3353. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  3354. .join('')
  3355. .replace(' ', '\\s*')
  3356. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  3357. 'i'),
  3358. can;
  3359. function deeper(spider)
  3360. {
  3361. let c, l, n;
  3362. if (words.test(spider.innerText))
  3363. {
  3364. if (spider.nodeType === Node.TEXT_NODE)
  3365. return true;
  3366. c = spider.childNodes;
  3367. l = c.length;
  3368. n = 0;
  3369. while(l--)
  3370. if (deeper(c[l]), can)
  3371. n++;
  3372. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  3373. can.push(spider);
  3374. return false;
  3375. }
  3376. return true;
  3377. }
  3378. function probe()
  3379. {
  3380. if (words.test(document.body.innerText))
  3381. {
  3382. can = [];
  3383. deeper(document.body);
  3384. let i = can.length, spider;
  3385. while(i--) {
  3386. spider = can[i];
  3387. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  3388. _setAttribute.call(spider, 'style', 'background:none!important');
  3389. }
  3390. }
  3391. }
  3392. (new MutationObserver(probe))
  3393. .observe(document, { childList:true, subtree:true });
  3394. }
  3395. };
  3396.  
  3397. scripts['auto.ru'] = () => {
  3398. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3399. let userAdsListAds = (
  3400. '.listing-list > .listing-item,'+
  3401. '.listing-item_type_fixed.listing-item'
  3402. );
  3403. let catalogAds = (
  3404. 'div[class*="layout_catalog-inline"],'+
  3405. 'div[class$="layout_horizontal"]'
  3406. );
  3407. let otherAds = (
  3408. '.advt_auto,'+
  3409. '.sidebar-block,'+
  3410. '.pager-listing + div[class],'+
  3411. '.card > div[class][style],'+
  3412. '.sidebar > div[class],'+
  3413. '.main-page__section + div[class],'+
  3414. '.listing > tbody'
  3415. );
  3416. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3417. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3418. gardener(otherAds, words);
  3419. };
  3420.  
  3421. scripts['rsload.net'] = {
  3422. load: () => {
  3423. let dis = document.querySelector('label[class*="cb-disable"]');
  3424. if (dis)
  3425. dis.click();
  3426. },
  3427. click: () => {
  3428. let t = e.target;
  3429. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3430. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3431. }
  3432. };
  3433.  
  3434. let domain;
  3435. // add alternative domain names if present and wrap functions into objects
  3436. for (let name in scripts)
  3437. {
  3438. if (scripts[name] instanceof Function)
  3439. scripts[name] = { now: scripts[name] };
  3440. for (domain of (scripts[name].other||[]))
  3441. {
  3442. if (domain in scripts)
  3443. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3444. scripts[domain] = scripts[name];
  3445. }
  3446. delete scripts[name].other;
  3447. }
  3448. // look for current domain in the list and run appropriate code
  3449. domain = document.domain;
  3450. while (domain.indexOf('.') > -1)
  3451. {
  3452. if (domain in scripts) for (let when in scripts[domain])
  3453. switch(when)
  3454. {
  3455. case 'now':
  3456. scripts[domain][when]();
  3457. break;
  3458. case 'dom':
  3459. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3460. break;
  3461. default:
  3462. document.addEventListener (when, scripts[domain][when], false);
  3463. }
  3464. domain = domain.slice(domain.indexOf('.') + 1);
  3465. }
  3466. })();