RU AdList JS Fixes

try to take over the world!

目前为 2017-09-29 提交的版本,查看 最新版本

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