RU AdList JS Fixes

try to take over the world!

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

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