RU AdList JS Fixes

try to take over the world!

当前为 2017-09-28 提交的版本,查看 最新版本

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