RU AdList JS Fixes

try to take over the world!

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

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