RU AdList JS Fixes

try to take over the world!

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

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