RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20170917.1
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @match *://*/*
  8. // @grant unsafeWindow
  9. // @grant window.close
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @run-at document-start
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let win = (unsafeWindow || window),
  18. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  19. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  20. isChrome = !!window.chrome && !!window.chrome.webstore,
  21. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  22. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  23. isFirefox = typeof InstallTrigger !== 'undefined',
  24. inIFrame = (win.self !== win.top),
  25. _getAttribute = Element.prototype.getAttribute,
  26. _setAttribute = Element.prototype.setAttribute,
  27. _de = document.documentElement,
  28. _appendChild = Document.prototype.appendChild.bind(_de),
  29. _removeChild = Document.prototype.removeChild.bind(_de),
  30. _createElement = Document.prototype.createElement.bind(document);
  31.  
  32. if (isFirefox && // Exit on image pages in Fx
  33. document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  34. return;
  35.  
  36. // dTree 2.05 in some cases replaces Node object before my script kicks in :(
  37. if (!Node.prototype)
  38. {
  39. let ifr = _createElement('iframe');
  40. _appendChild(ifr);
  41. try {
  42. window.Node = ifr.contentWindow.Node;
  43. console.log('Node object restored. -_-');
  44. } catch(e) {
  45. console.log('Unable to restore Node object.', e);
  46. }
  47. _removeChild(ifr);
  48. }
  49.  
  50. // NodeList iterator polyfill (mostly for Safari)
  51. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  52. if (!NodeList.prototype[Symbol.iterator]) {
  53. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  54. }
  55.  
  56. // Options
  57. let opts = {
  58. 'useWSIFunc': useWSI
  59. };
  60.  
  61. {
  62. let optsCall = function(callback)
  63. {
  64. // Register event listener
  65. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  66. cb = callback.func.bind(callback.name);
  67. window.addEventListener(key, cb, false);
  68. // Generate and dispatch synthetic event
  69. let ev = document.createEvent("HTMLEvents");
  70. ev.initEvent(key, true, false);
  71. window.dispatchEvent(ev);
  72. // Remove listener
  73. window.removeEventListener(key, cb, false);
  74. };
  75.  
  76. let initOptsHandler = function()
  77. {
  78. opts[this] = GM_getValue(this, true);
  79. if (opts[this])
  80. opts[this+'Func']();
  81. };
  82.  
  83. optsCall({
  84. func: initOptsHandler,
  85. name: 'useWSI'
  86. });
  87.  
  88. // show options page
  89. let openOptions = function()
  90. {
  91. let ovl = _createElement('div'),
  92. inner = _createElement('div');
  93. ovl.style = (
  94. 'position: fixed;'+
  95. 'top:0; left:0;'+
  96. 'bottom: 0; right: 0;'+
  97. 'background: rgba(0,0,0,0.85);'+
  98. 'z-index: 2147483647;'+
  99. 'padding: 5em'
  100. );
  101. inner.style = (
  102. 'background: whitesmoke;'+
  103. 'font-size: 10pt;'+
  104. 'color: black;'+
  105. 'padding: 1em'
  106. );
  107. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  108. inner.appendChild(_createElement('br'));
  109. inner.appendChild(_createElement('br'));
  110. ovl.addEventListener(
  111. 'click', function(e)
  112. {
  113. if (e.target === ovl) {
  114. ovl.parentNode.removeChild(ovl);
  115. e.preventDefault();
  116. }
  117. e.stopPropagation();
  118. }, false
  119. );
  120. // append checkbox with label function
  121. function addCheckbox(optName, optLabel)
  122. {
  123. let c = _createElement('input'),
  124. l = _createElement('label');
  125. c.type = 'checkbox';
  126. c.id = optName;
  127. optsCall({
  128. func: function()
  129. {
  130. c.checked = GM_getValue(this);
  131. },
  132. name: optName
  133. });
  134. c.addEventListener(
  135. 'click', function(e)
  136. {
  137. optsCall({
  138. func:function(){
  139. GM_setValue(this, e.target.checked);
  140. opts[this] = e.target.checked;
  141. },
  142. name:optName
  143. });
  144. }, true
  145. );
  146. l.textContent = optLabel;
  147. l.setAttribute('for', optName);
  148. inner.appendChild(c);
  149. inner.appendChild(l);
  150. inner.appendChild(_createElement('br'));
  151. }
  152. // append checkboxes
  153. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  154. document.body.appendChild(ovl);
  155. ovl.appendChild(inner);
  156. };
  157.  
  158. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  159. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  160. document.addEventListener(
  161. 'keydown', function(e)
  162. {
  163. if ((e.code === opKey[opPos] || e.location) &&
  164. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  165. {
  166. opPos += e.location ? 0 : 1;
  167. e.stopPropagation();
  168. e.preventDefault();
  169. } else {
  170. opPos = 0;
  171. }
  172. if (opPos === opKey.length)
  173. {
  174. opPos = 0;
  175. openOptions();
  176. }
  177. }, false
  178. );
  179. }
  180.  
  181. // Special wrapper script to run scripts designed to override standard DOM functions
  182. // In Firefox appends supplied script to a page to make it run in page context and let
  183. // page content access overridden functions. In other browsers just run it as-is.
  184. function scriptLander(func, prepend)
  185. {
  186. if (!isFirefox)
  187. {
  188. func();
  189. return;
  190. }
  191. let script = _createElement('script');
  192. let inline = ['string', 'function'];
  193. script.textContent = '!function(){let win=window;' + (
  194. inline.includes(typeof prepend) && prepend ||
  195. prepend instanceof Array && prepend.join(';') || ''
  196. ) + ';!' + func + '();}();';
  197. _appendChild(script);
  198. _removeChild(script);
  199. }
  200.  
  201. function nullTools(log) {
  202. // jshint validthis:true
  203. let nt = this;
  204. function trace() { if (log) console.trace.apply(this, arguments); }
  205.  
  206. nt.define = function(obj, prop, val)
  207. {
  208. Object.defineProperty(
  209. obj, prop, {
  210. get: () => (trace('get', prop, 'of', obj, 'which is', val), val),
  211. set: (v) => (trace('set', prop, 'of', obj, 'to', v), 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. /^\/(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.  
  1092. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/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. function hide(node) {
  1125. if (_getAttribute.call(node, 'style') === 'display: none !important')
  1126. return false;
  1127. console.log('Hid node.');
  1128. _setAttribute.call(node, 'style', 'display: none !important');
  1129. return true;
  1130. }
  1131. // Search ads
  1132. function removeSearchAds()
  1133. {
  1134. let res = false;
  1135. // hide unparsed Yandex ads if present
  1136. for (let node of _querySelectorAll('.serp-item[role="complementary"]'))
  1137. res = res|hide(node);
  1138. if (res) return 'Unparsed Yandex ads were hidden.';
  1139. // build list of ids related to natural results
  1140. let ids = [];
  1141. for (let style of _querySelectorAll('style[data-as^="serp-label"]'))
  1142. ids.push(style.textContent.replace(/\{.*\}/,'').trim());
  1143. // hide result nodes which doesn't contains any ids from the list (ads)
  1144. let nodes = _querySelectorAll('.serp-item[data-cid] > .organic');
  1145. if (ids.length > 0)
  1146. {
  1147. for (let node of nodes)
  1148. if (!node.querySelector(ids.join(',')))
  1149. res = res|hide(node.parentNode);
  1150. } else {
  1151. for (let node of nodes)
  1152. {
  1153. let label = (node.querySelector('.label')||{}).textContent;
  1154. if (adWords[1].test(label) || adWords[2].test(label))
  1155. res = res|hide(node.parentNode);
  1156. }
  1157. }
  1158. if (res)
  1159. return 'Parsed Yandex ads were hidden.';
  1160. else
  1161. return 'No ads were detected.';
  1162. }
  1163. function removeSearchAdsLog()
  1164. {
  1165. let res = removeSearchAds();
  1166. if (res) console.log(res);
  1167. }
  1168. // News ads
  1169. function removeNewsAds()
  1170. {
  1171. for (let node of _querySelectorAll('style[nonce]'))
  1172. remove(node);
  1173. let news = new Set(), to_remove = [];
  1174. for (let node of _querySelectorAll('.profit .story_view_normal, .profit .widget'))
  1175. if (news.has(node.textContent) || adWords[0].test(node.textContent))
  1176. hide(node);
  1177. else
  1178. news.add(node.textContent);
  1179. news.clear();
  1180. }
  1181. // Music ads
  1182. function removeMusicAds()
  1183. {
  1184. for (let node of _querySelectorAll('.ads-block'))
  1185. remove(node);
  1186. }
  1187. // Mail ads
  1188. function removeMailAds()
  1189. {
  1190. let slice = Array.prototype.slice,
  1191. nodes = slice.call(_querySelectorAll('.ns-view-folders')),
  1192. node, len, cls;
  1193.  
  1194. for (node of nodes)
  1195. if (!len || len > node.classList.length)
  1196. len = node.classList.length;
  1197.  
  1198. node = nodes.pop();
  1199. while (node)
  1200. {
  1201. if (node.classList.length > len)
  1202. for (cls of slice.call(node.classList))
  1203. if (cls.indexOf('-') === -1)
  1204. {
  1205. remove(node);
  1206. break;
  1207. }
  1208. node = nodes.pop();
  1209. }
  1210. }
  1211. // News fixes
  1212. function removePageAdsClass()
  1213. {
  1214. if (document.body.classList.contains("b-page_ads_yes"))
  1215. {
  1216. document.body.classList.remove("b-page_ads_yes");
  1217. console.log('Page ads class removed.');
  1218. }
  1219. }
  1220. // Function to attach an observer to monitor dynamic changes on the page
  1221. function pageUpdateObserver(func, obj, params) {
  1222. if (obj)
  1223. (new MutationObserver(func))
  1224. .observe(obj, (params || { childList:true, subtree:true }));
  1225. }
  1226.  
  1227. if (win.location.hostname.search(/^mail\./i) === 0) {
  1228. pageUpdateObserver(
  1229. function(ms, o)
  1230. {
  1231. let aside = _querySelector('.mail-Layout-Aside');
  1232. if (aside) {
  1233. o.disconnect();
  1234. pageUpdateObserver(removeMailAds, aside);
  1235. }
  1236. }, document.body
  1237. );
  1238. removeMailAds();
  1239. } else if (win.location.hostname.search(/^music\./i) === 0) {
  1240. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1241. removeMusicAds();
  1242. } else if (win.location.hostname.search(/^news\./i) === 0) {
  1243. pageUpdateObserver(removeNewsAds, document.body);
  1244. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1245. removeNewsAds();
  1246. removePageAdsClass();
  1247. } else {
  1248. pageUpdateObserver(removeSearchAdsLog, _querySelector('.main__content'));
  1249. removeSearchAdsLog();
  1250. }
  1251. }
  1252. );
  1253. }
  1254.  
  1255. // Yandex Link Tracking
  1256. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1257. {
  1258. let fakeRoot = {
  1259. firstChild: null,
  1260. appendChild: ()=>null,
  1261. querySelector: ()=>null,
  1262. querySelectorAll: ()=>null
  1263. };
  1264. Element.prototype.createShadowRoot = () => fakeRoot;
  1265. Object.defineProperty(Element.prototype, "shadowRoot", {
  1266. value: fakeRoot,
  1267. enumerable: true,
  1268. configurable: false
  1269. });
  1270. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1271. let selectors = (
  1272. 'A[onmousedown*="/jsredir"],'+
  1273. 'A[data-vdir-href],'+
  1274. 'A[data-counter]'
  1275. );
  1276. let removeTrackingAttributes = function(link)
  1277. {
  1278. link.removeAttribute('onmousedown');
  1279. if (link.hasAttribute('data-vdir-href')) {
  1280. link.removeAttribute('data-vdir-href');
  1281. link.removeAttribute('data-orig-href');
  1282. }
  1283. if (link.hasAttribute('data-counter')) {
  1284. link.removeAttribute('data-counter');
  1285. link.removeAttribute('data-bem');
  1286. }
  1287. };
  1288. let removeTracking = function(scope)
  1289. {
  1290. for (let link of scope.querySelectorAll(selectors))
  1291. removeTrackingAttributes(link);
  1292. };
  1293. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1294. (new MutationObserver(
  1295. function(ms)
  1296. {
  1297. let m, node;
  1298. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1299. if (node.tagName === 'A' && node.matches(selectors)) {
  1300. removeTrackingAttributes(node);
  1301. } else {
  1302. removeTracking(node);
  1303. }
  1304. }
  1305. )).observe(_de, { childList: true, subtree: true });
  1306.  
  1307. //skip fixes for other sites
  1308. return;
  1309. }
  1310.  
  1311. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1312. document.addEventListener(
  1313. 'DOMContentLoaded', function()
  1314. {//createPlayer();
  1315. function log (e) {
  1316. console.log('Player FIX: Detected', e, 'player in', win.location.href);
  1317. }
  1318. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1319. {
  1320. log('Moonwalk');
  1321. if (win.adv_enabled)
  1322. win.adv_enabled = false;
  1323. win.condition_detected = false;
  1324. if (win.MXoverrollCallback)
  1325. document.addEventListener(
  1326. 'click', function catcher(e)
  1327. {
  1328. e.stopPropagation();
  1329. win.MXoverrollCallback.call(window);
  1330. document.removeEventListener('click', catcher, true);
  1331. }, true
  1332. );
  1333. }
  1334. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1335. {
  1336. log('HDGo');
  1337. document.body.onclick = null;
  1338. let tmp = document.querySelector('#swtf');
  1339. if (tmp)
  1340. tmp.style.display = 'none';
  1341. if (win.banner_second !== undefined)
  1342. win.banner_second = 0;
  1343. if (win.$banner_ads !== undefined)
  1344. win.$banner_ads = false;
  1345. if (win.$new_ads !== undefined)
  1346. win.$new_ads = false;
  1347. if (win.createCookie !== undefined)
  1348. win.createCookie('popup', 'true', '999');
  1349. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1350. win.canRunAds = true;
  1351. }
  1352. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1353. {
  1354. log('Kodik');
  1355. let tmp = document.querySelector('.play_button');
  1356. if (tmp)
  1357. tmp.onclick = win.MXoverrollCallback.bind(window);
  1358. win.IsAdBlock = false;
  1359. }
  1360. else if (win.getnextepisode && win.uppodEvent)
  1361. {
  1362. log('Share-Serials.net');
  1363. scriptLander(
  1364. function()
  1365. {
  1366. let _setInterval = win.setInterval,
  1367. _setTimeout = win.setTimeout;
  1368. win.setInterval = function(func)
  1369. {
  1370. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1371. {
  1372. let intv = _setInterval.call(
  1373. this, function()
  1374. {
  1375. _setTimeout.call(
  1376. this, function(intv)
  1377. {
  1378. clearInterval(intv);
  1379. let timer = document.querySelector('#timer');
  1380. if (timer)
  1381. timer.click();
  1382. }, 100, intv);
  1383. func.call(this);
  1384. }, 5
  1385. );
  1386.  
  1387. return intv;
  1388. }
  1389. return _setInterval.apply(this, arguments);
  1390. };
  1391. win.setTimeout = function(func) {
  1392. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1393. {
  1394. return _setTimeout.call(this, func, 0);
  1395. }
  1396. return _setTimeout.apply(this, arguments);
  1397. };
  1398. }
  1399. );
  1400. }
  1401. }, false
  1402. );
  1403.  
  1404. // piguiqproxy.com circumvention prevention
  1405. scriptLander(
  1406. function()
  1407. {
  1408. let _open = XMLHttpRequest.prototype.open;
  1409. let blacklist = /[/.@](piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1410. XMLHttpRequest.prototype.open = function(method, url)
  1411. {
  1412. if (method === 'GET' && blacklist.test(url))
  1413. {
  1414. this.send = () => null;
  1415. this.setRequestHeader = () => null;
  1416. console.log('Blocked request: ', url);
  1417. return;
  1418. }
  1419. return _open.apply(this, arguments);
  1420. };
  1421. }
  1422. );
  1423.  
  1424. // === Helper functions ===
  1425.  
  1426. // function to search and remove nodes by content
  1427. // selector - standard CSS selector to define set of nodes to check
  1428. // words - regular expression to check content of the suspicious nodes
  1429. // params - object with multiple extra parameters:
  1430. // .log - display log in the console
  1431. // .hide - set display to none instead of removing from the page
  1432. // .parent - parent node to remove if content is found in the child node
  1433. // .siblings - number of simling nodes to remove (excluding text nodes)
  1434. let scRemove = (node) => node.parentNode.removeChild(node);
  1435. let scHide = function(node)
  1436. {
  1437. let style = _getAttribute.call(node, 'style') || '',
  1438. hide = ';display:none!important;';
  1439. if (style.indexOf(hide) < 0)
  1440. _setAttribute.call(node, 'style', style + hide);
  1441. };
  1442. function scissors (selector, words, scope, params)
  1443. {
  1444. if (params.log)
  1445. console.log('[s] starting with', selector, words, scope, JSON.stringify(params));
  1446. let remFunc = (params.hide ? scHide : scRemove),
  1447. iterFunc = (params.siblings > 0 ? 'nextSibling' : 'previousSibling'),
  1448. toRemove = [],
  1449. siblings;
  1450. for (let node of scope.querySelectorAll(selector))
  1451. {
  1452. if (params.log)
  1453. console.log('[s] found node', node);
  1454. if (params.parent)
  1455. {
  1456. while(node !== scope && !(node.matches(params.parent)))
  1457. node = node.parentNode;
  1458. if (params.log)
  1459. console.log('[s] moving to parent node', node);
  1460. if (node === scope)
  1461. {
  1462. if (params.log)
  1463. console.log('[s] reached scope node, nothing to remove here.');
  1464. break;
  1465. }
  1466. }
  1467. if (words.test(node.innerHTML) || !node.childNodes.length)
  1468. {
  1469. // drill up to the specified parent node if required
  1470. if (toRemove.indexOf(node) === -1)
  1471. {
  1472. if (params.log)
  1473. console.log('[s] adding node into list for removal');
  1474. toRemove.push(node);
  1475. // add multiple nodes if defined more than one sibling
  1476. siblings = Math.abs(params.siblings) || 0;
  1477. while (siblings)
  1478. {
  1479. node = node[iterFunc];
  1480. if (node.nodeType === Node.ELEMENT_NODE)
  1481. {
  1482. if (params.log)
  1483. console.log('[s] adding sibling node', node);
  1484. toRemove.push(node);
  1485. siblings -= 1; //count only element nodes
  1486. }
  1487. else if (!params.hide)
  1488. {
  1489. if (params.log)
  1490. console.log('[s] adding sibling node', node);
  1491. toRemove.push(node);
  1492. }
  1493. }
  1494. } else {
  1495. if (params.log)
  1496. console.log('[s] node already marked for removal');
  1497. }
  1498. } else {
  1499. if (params.log)
  1500. console.log('[s] word test failed, proceed to the next node');
  1501. }
  1502. }
  1503. if (params.log)
  1504. console.log('[s] proceeding with', (params.hide?'hide':'removal'), 'of', toRemove);
  1505. for (let node of toRemove)
  1506. remFunc(node);
  1507.  
  1508. return toRemove.length;
  1509. }
  1510.  
  1511. // function to perform multiple checks if ads inserted with a delay
  1512. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1513. // also does 1 extra check when a page completely loads
  1514. // selector and words - passed dow to scissors
  1515. // params - object with multiple extra parameters:
  1516. // .log - display log in the console
  1517. // .root - selector to narrow down scope to scan;
  1518. // .observe - if true then check will be performed continuously;
  1519. // Other parameters passed down to scissors.
  1520. function gardener(selector, words, params)
  1521. {
  1522. params = params || {};
  1523. if (params.log)
  1524. console.log('[g] starting with', selector, words, JSON.stringify(params));
  1525. let scope = document,
  1526. nonstop = false;
  1527. // narrow down scope to a specific element
  1528. if (params.root)
  1529. {
  1530. scope = scope.querySelector(params.root);
  1531. if (!scope) // exit if the root element is not present on the page
  1532. return 0;
  1533. if (params.log)
  1534. console.log('[g] scope', scope);
  1535. }
  1536. // add observe mode if required
  1537. if (params.observe)
  1538. {
  1539. if (typeof MutationObserver === 'function')
  1540. {
  1541. (new MutationObserver(
  1542. function(ms)
  1543. {
  1544. for (let m of ms) if (m.addedNodes.length)
  1545. scissors(selector, words, scope, params);
  1546. }
  1547. )).observe(scope, { childList:true, subtree: true });
  1548. if (params.log)
  1549. console.log('[g] observer enabled');
  1550. } else {
  1551. nonstop = true;
  1552. if (params.log)
  1553. console.log('[g] nonstop mode enabled');
  1554. }
  1555. }
  1556. // wait for a full page load to do one extra cut
  1557. win.addEventListener(
  1558. 'load', function()
  1559. {
  1560. if (params.log)
  1561. console.log('[g] onload cleanup');
  1562. scissors(selector, words, scope, params);
  1563. }
  1564. );
  1565. // do multiple cuts during page load until ads removed
  1566. function cut(sci, s, w, sc, p, i)
  1567. {
  1568. if (i > 0)
  1569. i -= 1;
  1570. if (i && !sci(s, w, sc, p))
  1571. setTimeout(cut, 100, sci, s, w, sc, p, i);
  1572. }
  1573. cut(scissors, selector, words, scope, params, (nonstop ? -1 : 30));
  1574. }
  1575.  
  1576. // wrap popular methods to open a new tab to catch specific behaviours
  1577. function createWindowOpenWrapper(openFunc, onClickFunc)
  1578. {
  1579. let _createElement = Document.prototype.createElement,
  1580. _appendChild = Element.prototype.appendChild;
  1581.  
  1582. function redefineOpen(obj)
  1583. {
  1584. Object.defineProperty(obj, 'open', {
  1585. get: () => openFunc,
  1586. set: (val) => val,
  1587. enumerable: true
  1588. });
  1589. }
  1590. redefineOpen(win);
  1591.  
  1592. Document.prototype.createElement = function createElement(name)
  1593. {
  1594. let el = _createElement.apply(this, arguments);
  1595. // click-dispatch check for Google Chrome and similar browsers
  1596. if (el instanceof HTMLAnchorElement)
  1597. el.addEventListener(
  1598. 'click', onClickFunc, false
  1599. );
  1600. // redefine window.open in first-party frames
  1601. if (el instanceof HTMLIFrameElement)
  1602. el.addEventListener(
  1603. 'load', function(e)
  1604. {
  1605. try {
  1606. redefineOpen(e.target.contentWindow);
  1607. } catch(ignore) {}
  1608. }, false
  1609. );
  1610. return el;
  1611. };
  1612.  
  1613. // wrap window.open in newly added first-party frames
  1614. Element.prototype.appendChild = function appendChild()
  1615. {
  1616. let el = _appendChild.apply(this, arguments);
  1617. if (el instanceof HTMLIFrameElement) {
  1618. try {
  1619. redefineOpen(el.contentWindow);
  1620. } catch(ignore) {}
  1621. }
  1622. return el;
  1623. };
  1624. }
  1625.  
  1626. // Function to catch and block various methods to open a new window with 3rd-party content.
  1627. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1628. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1629. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1630. // node or simply a link with piece of javascript code in the HREF attribute.
  1631. function preventPopups()
  1632. {
  1633. if (inIFrame)
  1634. {
  1635. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1636. return;
  1637. }
  1638.  
  1639. scriptLander(
  1640. function()
  1641. {
  1642. function open()
  1643. {
  1644. '[native code]';
  1645. console.log('Site attempted to open a new window', arguments);
  1646. return {
  1647. document: {
  1648. write: () => {},
  1649. writeln: () => {}
  1650. }
  1651. };
  1652. }
  1653.  
  1654. function clickHandler(e)
  1655. {
  1656. let link = e.target;
  1657. if (!link.parentNode || !e.isTrusted ||
  1658. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  1659. {
  1660. e.preventDefault();
  1661. console.log('Blocked suspicious click event', e, 'on', e.target);
  1662. }
  1663. }
  1664.  
  1665. createWindowOpenWrapper(open, clickHandler);
  1666.  
  1667. console.log('Popup prevention enabled.');
  1668. }, createWindowOpenWrapper
  1669. );
  1670. }
  1671.  
  1672. // Helper function to close background tab if site opens itself in a new tab and then
  1673. // loads a 3rd-party page in the background one (thus performing background redirect).
  1674. function preventPopunders()
  1675. {
  1676. // create "close_me" event to call high-level window.close()
  1677. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1678. let callClose = () => (console.log('close call'), window.close());
  1679. window.addEventListener(eventName, callClose, true);
  1680.  
  1681. scriptLander(
  1682. function()
  1683. {
  1684. let _open = window.open,
  1685. parseURL = document.createElement('A');
  1686. // get host of a provided URL with help of an anchor object
  1687. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1688. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1689. // site went to a new tab and attempts to unload
  1690. // call for high-level close through event
  1691. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1692. // check is URL local or goes to different site
  1693. function isLocal(url)
  1694. {
  1695. let loc = window.location;
  1696. if (url === loc.pathname || url === loc.href)
  1697. return true; // URL points to current pathname or full address
  1698. let host = getHost(url),
  1699. site = loc.host;
  1700. if (host === '')
  1701. return false; // URLs with unusual protocol may have empty 'host'
  1702. if (host.length > site.length)
  1703. [site, host] = [host, site];
  1704. return site.includes(host, site.length - host.length);
  1705. }
  1706.  
  1707. function open(url)
  1708. {
  1709. '[native code]';
  1710. if (url && isLocal(url))
  1711. window.addEventListener('unload', closeWindow, true);
  1712. // jshint validthis:true
  1713. return _open.apply(this, arguments);
  1714. }
  1715.  
  1716. function clickHandler(e)
  1717. {
  1718. if (!e.target.parentNode || !e.isTrusted)
  1719. window.addEventListener('unload', closeWindow, true);
  1720. }
  1721.  
  1722. createWindowOpenWrapper(open, clickHandler);
  1723.  
  1724. console.log("Background redirect prevention enabled.");
  1725. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1726. );
  1727. }
  1728.  
  1729. // Mix between check for popups and popunders
  1730. // Significantly more agressive than both and can't be used as universal solution
  1731. function preventPopMix()
  1732. {
  1733. if (inIFrame)
  1734. {
  1735. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1736. return;
  1737. }
  1738.  
  1739. // create "close_me" event to call high-level window.close()
  1740. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1741. let callClose = () => (console.log('close call'), window.close());
  1742. window.addEventListener(eventName, callClose, true);
  1743.  
  1744. scriptLander(
  1745. function()
  1746. {
  1747. let _open = window.open,
  1748. parseURL = document.createElement('A');
  1749. // get host of a provided URL with help of an anchor object
  1750. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1751. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1752. // site went to a new tab and attempts to unload
  1753. // call for high-level close through event
  1754. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  1755. // check is URL local or goes to different site
  1756. function isLocal(url)
  1757. {
  1758. let loc = window.location;
  1759. if (url === loc.pathname || url === loc.href)
  1760. return true; // URL points to current pathname or full address
  1761. let host = getHost(url),
  1762. site = loc.host;
  1763. if (host === '')
  1764. return false; // URLs with unusual protocol may have empty 'host'
  1765. if (host.length > site.length)
  1766. [site, host] = [host, site];
  1767. return site.includes(host, site.length - host.length);
  1768. }
  1769.  
  1770. // add check for redirect for 5 seconds, then disable it
  1771. function checkRedirect()
  1772. {
  1773. window.addEventListener('unload', closeWindow, true);
  1774. setTimeout(closeWindow=>window.removeEventListener('unload', closeWindow, true), 5000, closeWindow);
  1775. }
  1776.  
  1777. function open(url, name)
  1778. {
  1779. '[native code]';
  1780. if (url && isLocal(url) && (!name || name === '_blank'))
  1781. {
  1782. console.log('Suspicious local new window', arguments);
  1783. checkRedirect();
  1784. // jshint validthis:true
  1785. return _open.apply(this, arguments);
  1786. }
  1787. console.log('Blocked attempt to open a new window', arguments);
  1788. return {
  1789. document: {
  1790. write: () => {},
  1791. writeln: () => {}
  1792. }
  1793. };
  1794. }
  1795.  
  1796. function clickHandler(e)
  1797. {
  1798. let link = e.target,
  1799. url = link.href||'';
  1800. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  1801. {
  1802. console.log('Link', link, 'were created dinamically, but looks fine.');
  1803. return true;
  1804. }
  1805. if (isLocal(url) && link.target === '_blank')
  1806. {
  1807. console.log('Suspicious local link', link);
  1808. checkRedirect();
  1809. return;
  1810. }
  1811. console.log('Blocked suspicious click on a link', link);
  1812. e.stopPropagation();
  1813. e.preventDefault();
  1814. }
  1815.  
  1816. createWindowOpenWrapper(open, clickHandler);
  1817.  
  1818. console.log("Mixed popups prevention enabled.");
  1819. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1820. );
  1821. }
  1822. // External listener for case when site known to open popups were loaded in iframe
  1823. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1824. // Some sites replace frame's window.location with data-url to run in clean context
  1825. if (!inIFrame)
  1826. {
  1827. window.addEventListener(
  1828. 'message', function(e)
  1829. {
  1830. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1831. return;
  1832. let src = e.data.href;
  1833. for (let frame of document.querySelectorAll('iframe'))
  1834. if (frame.contentWindow === e.source)
  1835. {
  1836. if (frame.hasAttribute('sandbox'))
  1837. {
  1838. if (!frame.sandbox.has('allow-popups'))
  1839. return; // exit frame since it's already sandboxed and popups are blocked
  1840. // remove allow-popups if frame already sandboxed
  1841. frame.sandbox.remove('allow-popups');
  1842. } else {
  1843. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1844. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1845. // but to apply content must be reloaded and this script will re-apply it in the result
  1846. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1847. }
  1848. console.log('Disallowed popups from iframe', frame);
  1849.  
  1850. // reload frame content to apply restrictions
  1851. if (!src) {
  1852. src = frame.src;
  1853. console.log('Unable to get current iframe location, reloading from src', src);
  1854. } else
  1855. console.log('Reloading iframe with URL', src);
  1856. frame.src = 'about:blank';
  1857. frame.src = src;
  1858. }
  1859. }, false
  1860. );
  1861. }
  1862.  
  1863. // === Scripts for specific domains ===
  1864.  
  1865. let scripts = {};
  1866. // prevent popups and redirects block
  1867. // Popups
  1868. scripts.preventPopups = {
  1869. other: [
  1870. 'biqle.ru',
  1871. 'chaturbate.com',
  1872. 'dfiles.ru',
  1873. 'hentaiz.org',
  1874. 'mirrorcreator.com',
  1875. 'online-multy.ru',
  1876. 'radikal.ru',
  1877. 'seedoff.cc', 'seedoff.tv',
  1878. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1879. 'unionpeer.com',
  1880. 'zippyshare.com'
  1881. ],
  1882. now: preventPopups
  1883. };
  1884. // Popunders (background redirect)
  1885. scripts.preventPopunders = {
  1886. other: [
  1887. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1888. 'perfectgirls.net'
  1889. ],
  1890. now: preventPopunders
  1891. };
  1892. // PopMix (both types of popups encountered on site)
  1893. scripts.preventPopMix = {
  1894. other: [
  1895. 'openload.co',
  1896. 'turbobit.net'
  1897. ],
  1898. now: preventPopMix
  1899. };
  1900.  
  1901. // other
  1902. scripts['2picsun.ru'] = {
  1903. other: [
  1904. 'pics2sun.ru', '3pics-img.ru'
  1905. ],
  1906. now: function() {
  1907. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  1908. }
  1909. };
  1910.  
  1911. scripts['4pda.ru'] = {
  1912. now: function()
  1913. {
  1914. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  1915. let hStyle,
  1916. isForum = document.location.href.search('/forum/') !== -1,
  1917. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  1918. afterClean = () => remove(hStyle);
  1919.  
  1920. function beforeClean()
  1921. {
  1922. // attach styles before document displayed
  1923. hStyle = createStyle([
  1924. 'html { overflow-y: scroll }',
  1925. 'section[id] {'+(
  1926. 'position: absolute;'+
  1927. 'width: 100%'
  1928. )+'}',
  1929. 'article + aside * { display: none !important }',
  1930. '#header + div:after {'+(
  1931. 'content: "";'+
  1932. 'position: fixed;'+
  1933. 'top: 0;'+
  1934. 'left: 0;'+
  1935. 'width: 100%;'+
  1936. 'height: 100%;'+
  1937. 'background-color: #E6E7E9'
  1938. )+'}',
  1939. // http://codepen.io/Beaugust/pen/DByiE
  1940. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  1941. 'article + aside:after {'+(
  1942. 'content: "";'+
  1943. 'position: absolute;'+
  1944. 'width: 150px;'+
  1945. 'height: 150px;'+
  1946. 'top: 150px;'+
  1947. 'left: 50%;'+
  1948. 'margin-top: -75px;'+
  1949. 'margin-left: -75px;'+
  1950. 'box-sizing: border-box;'+
  1951. 'border-radius: 100%;'+
  1952. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  1953. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  1954. 'animation: spin 2s infinite linear'
  1955. )+'}'
  1956. ], {id:'ubrHider'}, true);
  1957.  
  1958. // display content of a page if time to load a page is more than 2 seconds to avoid
  1959. // blocking access to a page if it is loading for too long or stuck in a loading state
  1960. setTimeout(2000, afterClean);
  1961. }
  1962.  
  1963. createStyle([
  1964. '#nav .use-ad { display: block !important }',
  1965. 'article:not(.post) + article:not(#id),'+
  1966. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  1967. ]);
  1968.  
  1969. if (!isForum)
  1970. beforeClean();
  1971.  
  1972. // save links to non-overridden functions to use later
  1973. let protectedElems;
  1974. // protect/hide changed attributes in case site attempt to restore them
  1975. function styleProtector(eventMode)
  1976. {
  1977. let _toLowerCase = String.prototype.toLowerCase,
  1978. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  1979. protectedElems = new WeakMap();
  1980. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  1981. {
  1982. let originalFunction = element.prototype[functionName];
  1983. element.prototype[functionName] = function wrapper()
  1984. {
  1985. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  1986. return returnIfProtected(this, arguments);
  1987. return originalFunction.apply(this, arguments);
  1988. };
  1989. }
  1990. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  1991. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  1992. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  1993. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  1994. if (!eventMode)
  1995. return protectedElems;
  1996. else
  1997. {
  1998. let e = document.createEvent('Event');
  1999. e.initEvent('protoOverride', false, false);
  2000. window.protectedElems = protectedElems;
  2001. window.dispatchEvent(e);
  2002. }
  2003. }
  2004. if (!isFirefox)
  2005. protectedElems = styleProtector(false);
  2006. else
  2007. {
  2008. let script = document.createElement('script');
  2009. script.textContent = '(' + styleProtector.toString() + ')(true);';
  2010. window.addEventListener(
  2011. 'protoOverride', function protoOverrideCallback(e)
  2012. {
  2013. if (win.protectedElems) {
  2014. protectedElems = win.protectedElems;
  2015. delete win.protectedElems;
  2016. }
  2017. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2018. }, true
  2019. );
  2020. _appendChild(script);
  2021. _removeChild(script);
  2022. }
  2023.  
  2024. // clean a page
  2025. window.addEventListener(
  2026. 'DOMContentLoaded', function()
  2027. {
  2028. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2029. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2030.  
  2031. if (isForum)
  2032. {
  2033. let si = document.querySelector('#logostrip');
  2034. if (si)
  2035. remove(si.parentNode.nextSibling);
  2036. }
  2037.  
  2038. if (document.location.href.search('/forum/dl/') !== -1) {
  2039. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  2040. ';background-color:black!important');
  2041. for (let itm of document.querySelectorAll('body>div'))
  2042. if (!itm.querySelector('.dw-fdwlink'))
  2043. remove(itm);
  2044. }
  2045.  
  2046. if (isForum) // Do not continue if it's a forum
  2047. return;
  2048.  
  2049. {
  2050. let si = document.querySelector('#header');
  2051. if (si)
  2052. {
  2053. let rem = si.previousSibling;
  2054. while (rem)
  2055. {
  2056. si = rem.previousSibling;
  2057. remove(rem);
  2058. rem = si;
  2059. }
  2060. }
  2061. }
  2062.  
  2063. for (let itm of document.querySelectorAll('#nav li[class]'))
  2064. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2065. remove(itm);
  2066.  
  2067. let style, result,
  2068. fakeStyles = new WeakMap(),
  2069. styleProxy = {
  2070. get: function(target, prop)
  2071. {
  2072. let fakeStyle = fakeStyles.get(target);
  2073. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2074. },
  2075. set: function(target, prop, value)
  2076. {
  2077. let fakeStyle = fakeStyles.get(target);
  2078. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2079. return value;
  2080. }
  2081. };
  2082. for (let itm of document.querySelectorAll('DIV, A'))
  2083. {
  2084. if (itm.tagName ==='DIV' &&
  2085. itm.offsetWidth > 0.95 * width() &&
  2086. itm.offsetHeight > 0.85 * height())
  2087. {
  2088. style = window.getComputedStyle(itm, null);
  2089. result = [];
  2090.  
  2091. if (style.backgroundImage !== 'none')
  2092. result.push('background-image:none!important');
  2093.  
  2094. if (style.backgroundColor !== 'transparent' &&
  2095. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2096. result.push('background-color:transparent!important');
  2097.  
  2098. if (result.length)
  2099. {
  2100. if (itm.getAttribute('style'))
  2101. result.unshift(itm.getAttribute('style'));
  2102.  
  2103. fakeStyles.set(itm.style, {
  2104. 'backgroundImage': itm.style.backgroundImage,
  2105. 'backgroundColor': itm.style.backgroundColor
  2106. });
  2107.  
  2108. try {
  2109. Object.defineProperty(itm, 'style', {
  2110. value: new Proxy(itm.style, styleProxy),
  2111. enumerable: true
  2112. });
  2113. } catch (e) {
  2114. console.log('Unable to protect style property.', e);
  2115. }
  2116.  
  2117. if (protectedElems)
  2118. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2119.  
  2120. _setAttribute.call(itm, 'style', result.join(';'));
  2121. }
  2122. }
  2123. if (itm.tagName ==='A' &&
  2124. (itm.offsetWidth > 0.95 * width() ||
  2125. itm.offsetHeight > 0.85 * height()))
  2126. {
  2127. if (protectedElems)
  2128. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2129.  
  2130. _setAttribute.call(itm, 'style', 'display:none!important');
  2131. }
  2132. }
  2133.  
  2134. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2135. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2136. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2137. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2138. remove(itm);
  2139.  
  2140. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2141.  
  2142. // display content of the page
  2143. afterClean();
  2144. }
  2145. );
  2146. }
  2147. };
  2148.  
  2149. scripts['allmovie.pro'] = {
  2150. other: ['rufilmtv.org'],
  2151. dom: function()
  2152. {
  2153. // pretend to be Android to make site use different played for ads
  2154. if (isSafari)
  2155. return;
  2156. Object.defineProperty(navigator, 'userAgent', {
  2157. 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'; },
  2158. enumerable: true
  2159. });
  2160. }
  2161. };
  2162.  
  2163. scripts['anidub-online.ru'] = {
  2164. other: ['online.anidub.com'],
  2165. dom: function()
  2166. {
  2167. if (win.ogonekstart1)
  2168. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2169. },
  2170. now: () => createStyle([
  2171. '.background {background: none!important;}',
  2172. '.background > script + div,'+
  2173. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2174. '{display:none!important}'
  2175. ])
  2176. };
  2177.  
  2178. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2179.  
  2180. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2181.  
  2182. scripts['gidonline.club'] = {
  2183. now: () => createStyle('.tray > div[style] {display: none!important}')
  2184. };
  2185.  
  2186. scripts['hdgo.cc'] = {
  2187. other: ['46.30.43.38', 'couber.be'],
  2188. now: () => (new MutationObserver(
  2189. function(ms)
  2190. {
  2191. let m, node;
  2192. for (m of ms) for (node of m.addedNodes)
  2193. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  2194. node.removeAttribute('onerror');
  2195. }
  2196. )).observe(document.documentElement, { childList:true, subtree: true })
  2197. };
  2198.  
  2199. scripts['gismeteo.ru'] = {
  2200. other: ['gismeteo.ua'],
  2201. dom: () => gardener('div > a[target^="_"]', /Яндекс\.Директ/i, { root: 'body', observe: true, parent: 'div[class*="frame"]'})
  2202. };
  2203.  
  2204. scripts['hdrezka.me'] = {
  2205. now: function()
  2206. {
  2207. Object.defineProperty(win, 'ab', {
  2208. value: false,
  2209. enumerable: true
  2210. });
  2211. },
  2212. dom: () => gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i)
  2213. };
  2214.  
  2215. scripts['imageban.ru'] = {
  2216. now: preventPopunders,
  2217. dom: () => win.addEventListener(
  2218. 'unload', function()
  2219. {
  2220. window.location.hash = 'x'+Math.random().toString(36).substr(2);
  2221. }, true
  2222. )
  2223. };
  2224.  
  2225. scripts['mail.ru'] = {
  2226. now: function()
  2227. {
  2228. // Trick to prevent mail.ru from removing 3rd-party styles
  2229. scriptLander(
  2230. () => Object.defineProperty(Object.prototype, 'restoreVisibility', {
  2231. get: () => (() => null),
  2232. set: () => null
  2233. })
  2234. );
  2235. /* Experimental code, disabled for end users for now
  2236. // Ads removal on e.mail.ru
  2237. if (window.location.host === 'e.mail.ru')
  2238. {
  2239. let selector = (
  2240. '.b-datalist div[class]:not([id]) > div[class]:not([class*="js-"]),'+
  2241. '.b-letter div[class]:not([id]) > div[class]:not([class*="js-"]):not([class*="drop"]):not([class*="letter"]):not([style]):not([id]),'+
  2242. 'div[id]:not([class]) > div[id][class]:not([class*="js-"]):not([class*="drop"]):not([style])'
  2243. );
  2244. let janitor = function(nodes)
  2245. {
  2246. let color;
  2247. for (let node of nodes)
  2248. {
  2249. if (node.nodeType !== Node.ELEMENT_NODE)
  2250. continue;
  2251. color = window.getComputedStyle(node).backgroundColor;
  2252. if (/^rgb\(/.test(color) && color !== 'rgb(255, 255, 255)')
  2253. {
  2254. node.style.display = 'none';
  2255. console.log('Hide node:', node);
  2256. }
  2257. }
  2258. };
  2259. janitor(document.querySelectorAll(selector));
  2260. (new MutationObserver(
  2261. function(ms)
  2262. {
  2263. for (let m of ms)
  2264. janitor(m.addedNodes);
  2265. }
  2266. )).observe(
  2267. document.documentElement, {
  2268. childList: true,
  2269. subtree: true
  2270. }
  2271. );
  2272. }
  2273. /**/
  2274. }
  2275. };
  2276.  
  2277. scripts['megogo.net'] = {
  2278. now: function()
  2279. {
  2280. Object.defineProperty(win, "adBlock", {
  2281. get: () => false,
  2282. set: () => null,
  2283. enumerable : true
  2284. });
  2285. Object.defineProperty(win, "showAdBlockMessage", {
  2286. get: () => (() => null),
  2287. set: () => null,
  2288. enumerable: true
  2289. });
  2290. }
  2291. };
  2292.  
  2293. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2294.  
  2295. scripts['overclockers.ru'] = {
  2296. now: function()
  2297. {
  2298. createStyle('.fixoldhtml {display:block!important}');
  2299. if (!isChrome && !isOpera)
  2300. return; // Looks like my code works only in Chrome-like browsers
  2301. let noContentYet = true;
  2302. function jWrap()
  2303. {
  2304. win.$ = new Proxy(
  2305. win.$, {
  2306. apply: function(_$, _this, args)
  2307. {
  2308. let _ret = _$.apply(_this, args);
  2309. if (_ret[0] === document.body)
  2310. _ret.html = () => console.log('Anti-adblock prevented.');
  2311. return _ret;
  2312. }
  2313. }
  2314. );
  2315. win.jQuery = win.$;
  2316. }
  2317. (function jReady()
  2318. {
  2319. if (!win.$ && noContentYet)
  2320. setTimeout(jReady, 0);
  2321. else
  2322. jWrap();
  2323. })();
  2324. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  2325. }
  2326. };
  2327. scripts['forums.overclockers.ru'] = {
  2328. now: function()
  2329. {
  2330. createStyle('.needblock {position: fixed; left: -10000px}');
  2331. Object.defineProperty(win, 'adblck', {
  2332. get: () => 'no',
  2333. set: () => null,
  2334. enumerable: true
  2335. });
  2336. }
  2337. };
  2338.  
  2339. scripts['pb.wtf'] = {
  2340. other: ['piratbit.org', 'piratbit.ru'],
  2341. dom: function()
  2342. {
  2343. createStyle('.reques,#result,tbody.row1:not([id]) {display: none !important}');
  2344. // image in the slider in the header
  2345. gardener('a[href^="/ex"],a[href$="=="]', /img/i, {root:'.release-navbar', observe:true, parent:'div'});
  2346. // ads in blocks on the page
  2347. gardener('a[href^="/topic/234257"]', /Как\sразместить/i, {siblings:-1, root:'#main_content', observe:true, parent:'span[style]'});
  2348. // line above topic content
  2349. gardener('.re_top1', /./, {root:'#main_content', parent:'.hidden-sm'});
  2350. }
  2351. };
  2352.  
  2353. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  2354.  
  2355. scripts['qrz.ru'] = {
  2356. now: function()
  2357. {
  2358. Object.defineProperty(win, 'ab', {
  2359. get:()=>false,
  2360. set:()=>null
  2361. });
  2362. Object.defineProperty(win, 'tryMessage', {
  2363. get:()=>(()=>null),
  2364. set:()=>null
  2365. });
  2366. }
  2367. };
  2368.  
  2369. scripts['razlozhi.ru'] = {
  2370. now: function()
  2371. {
  2372. for (let func of ['createShadowRoot', 'attachShadow'])
  2373. if (func in Element.prototype)
  2374. Element.prototype[func] = function(){ return this.cloneNode(); };
  2375. }
  2376. };
  2377.  
  2378. scripts['rbc.ru'] = {
  2379. dom: function()
  2380. {
  2381. let _preventDefault = Event.prototype.preventDefault;
  2382. Event.prototype.preventDefault = function preventDefault()
  2383. {
  2384. let t = this.target;
  2385. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2386. throw new Error('an.yandex redirect prevention');
  2387. return _preventDefault.call(this);
  2388. };
  2389.  
  2390. function cleaner(nodes)
  2391. {
  2392. for (let node of nodes)
  2393. {
  2394. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2395. continue;
  2396. node.classList.remove('js-yandex-counter');
  2397. node.removeAttribute('data-yandex-name');
  2398. node.removeAttribute('data-yandex-params');
  2399. }
  2400. }
  2401. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2402.  
  2403. (new MutationObserver(
  2404. ms => { for (let m of ms) cleaner(m.addedNodes); }
  2405. )).observe(_de, {childList: true, subtree: true});
  2406. }
  2407. };
  2408.  
  2409. scripts['rp5.ru'] = {
  2410. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2411. dom: function()
  2412. {
  2413. createStyle('#bannerBottom {display: none!important}');
  2414. let co = document.querySelector('#content');
  2415. if (!co)
  2416. return;
  2417. let nodes = co.parentNode.childNodes,
  2418. i = nodes.length;
  2419. while (i--)
  2420. if (nodes[i] !== co)
  2421. nodes[i].parentNode.removeChild(nodes[i]);
  2422. }
  2423. };
  2424.  
  2425. scripts['rustorka.com'] = {
  2426. other: ['rumedia.ws'],
  2427. now: function()
  2428. {
  2429. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  2430. id: 'tempHidingStyles'
  2431. }, true);
  2432. preventPopups();
  2433. },
  2434. dom: function()
  2435. {
  2436. for (let o of document.querySelectorAll('IMG, A'))
  2437. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2438. (o.clientWidth === 300 && o.clientHeight === 250))
  2439. {
  2440. while (o && o.tagName !== 'A')
  2441. o = o.parentNode;
  2442. if (o)
  2443. _setAttribute.call(o, 'style', 'display: none !important');
  2444. }
  2445. let s = document.querySelector('#tempHidingStyles');
  2446. s.parentNode.removeChild(s);
  2447. }
  2448. };
  2449.  
  2450. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2451.  
  2452. scripts['sports.ru'] = function()
  2453. {
  2454. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2455. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2456. // extra functionality: shows/hides panel at the top depending on scroll direction
  2457. createStyle([
  2458. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2459. '.user-panel-up { top: -40px!important }'
  2460. ], {id: 'userPanelSlide'}, false);
  2461. (function lookForPanel()
  2462. {
  2463. let panel = document.querySelector('.user-panel__fixed');
  2464. if (!panel)
  2465. setTimeout(lookForPanel, 100);
  2466. else
  2467. window.addEventListener(
  2468. 'wheel', function(e)
  2469. {
  2470. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2471. panel.classList.add('user-panel-up');
  2472. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2473. panel.classList.remove('user-panel-up');
  2474. }, false
  2475. );
  2476. })();
  2477. };
  2478.  
  2479. scripts['vk.com'] = () => gardener((
  2480. '#wk_content > #wl_post > div,'+
  2481. '#page_wall_posts > div[id^="post-"],'+
  2482. 'div[class^="feed_row "] > div[id^="post-"],'+
  2483. 'div[class^="feed_row "] > div[id^="feed_repost-"]'
  2484. ), /wall_marked_as_ads/, {root: 'body', observe: true});
  2485.  
  2486. scripts['yap.ru'] = {
  2487. other: ['yaplakal.com'],
  2488. dom: function()
  2489. {
  2490. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2491. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2492. }
  2493. };
  2494.  
  2495. scripts['rambler.ru'] = {
  2496. other: ['championat.com','gazeta.ru','lenta.ru'],
  2497. now: () => scriptLander(
  2498. function()
  2499. {
  2500. let getDomain = (name) => name.replace(/[^:]+:\/\/([^:/]+)[:/].*/, '$1').replace(/[^.]+\./,'');
  2501. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload');
  2502. let _set = _onload.set;
  2503. _onload.configurable = false;
  2504. _onload.set = function(func)
  2505. {
  2506. _set.call(
  2507. this, function(e)
  2508. {
  2509. let d = e.target.href ? getDomain(e.target.href) : null,
  2510. h = window.location.host;
  2511. if (d && e.target instanceof HTMLLinkElement &&
  2512. (d === 'rambler.ru' || d === h || h.indexOf('.'+d) > -1))
  2513. {
  2514. console.log('Blocked "onload" for', e.target.href);
  2515. return false;
  2516. }
  2517. return func.apply(this, arguments);
  2518. }
  2519. );
  2520. };
  2521. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  2522. // fake global Adf object
  2523. let nt = new nullTools();
  2524. nt.define(win, 'Adf', nt.proxy({
  2525. banner: nt.proxy({
  2526. sspScroll: nt.func(),
  2527. ssp: nt.func()
  2528. })
  2529. }));
  2530. // extra script for partner news on gazeta.ru
  2531. if (!location.host.includes('gazeta.ru'))
  2532. return;
  2533. (new MutationObserver(
  2534. function(ms)
  2535. {
  2536. let m, node, header;
  2537. for (m of ms) for (node of m.addedNodes)
  2538. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  2539. {
  2540. header = node.querySelector('.sausage-header');
  2541. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  2542. node.style.display = 'none';
  2543. }
  2544. }
  2545. )).observe(document.documentElement, { childList:true, subtree: true });
  2546. }, nullTools
  2547. )
  2548. };
  2549.  
  2550. scripts['reactor.cc'] = {
  2551. other: ['joyreactor.cc', 'pornreactor.cc'],
  2552. now: function()
  2553. {
  2554. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  2555. },
  2556. click: function(e)
  2557. {
  2558. let node = e.target;
  2559. if (node.nodeType === Node.ELEMENT_NODE &&
  2560. node.style.position === 'absolute' &&
  2561. node.style.zIndex > 0)
  2562. node.parentNode.removeChild(node);
  2563. },
  2564. dom: function()
  2565. {
  2566. let words = new RegExp(
  2567. 'блокировщика рекламы'
  2568. .split('')
  2569. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2570. .join('')
  2571. .replace(' ', '\\s*')
  2572. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2573. 'i'),
  2574. can;
  2575. function deeper(spider)
  2576. {
  2577. let c, l, n;
  2578. if (words.test(spider.innerText))
  2579. {
  2580. if (spider.nodeType === Node.TEXT_NODE)
  2581. return true;
  2582. c = spider.childNodes;
  2583. l = c.length;
  2584. n = 0;
  2585. while(l--)
  2586. if (deeper(c[l]), can)
  2587. n++;
  2588. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2589. can.push(spider);
  2590. return false;
  2591. }
  2592. return true;
  2593. }
  2594. function probe()
  2595. {
  2596. if (words.test(document.body.innerText))
  2597. {
  2598. can = [];
  2599. deeper(document.body);
  2600. let i = can.length, spider;
  2601. while(i--) {
  2602. spider = can[i];
  2603. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2604. _setAttribute.call(spider, 'style', 'background:none!important');
  2605. }
  2606. }
  2607. }
  2608. (new MutationObserver(probe))
  2609. .observe(document, { childList:true, subtree:true });
  2610. }
  2611. };
  2612.  
  2613. scripts['auto.ru'] = function()
  2614. {
  2615. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2616. let userAdsListAds = (
  2617. '.listing-list > .listing-item,'+
  2618. '.listing-item_type_fixed.listing-item'
  2619. );
  2620. let catalogAds = (
  2621. 'div[class*="layout_catalog-inline"],'+
  2622. 'div[class$="layout_horizontal"]'
  2623. );
  2624. let otherAds = (
  2625. '.advt_auto,'+
  2626. '.sidebar-block,'+
  2627. '.pager-listing + div[class],'+
  2628. '.card > div[class][style],'+
  2629. '.sidebar > div[class],'+
  2630. '.main-page__section + div[class],'+
  2631. '.listing > tbody'
  2632. );
  2633. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2634. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2635. gardener(otherAds, words);
  2636. };
  2637.  
  2638. scripts['rsload.net'] = {
  2639. load: function()
  2640. {
  2641. let dis = document.querySelector('label[class*="cb-disable"]');
  2642. if (dis)
  2643. dis.click();
  2644. },
  2645. click: function(e)
  2646. {
  2647. let t = e.target;
  2648. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2649. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2650. }
  2651. };
  2652.  
  2653. let domain, name;
  2654. // add alternate domain names if present
  2655. for (name in scripts) if (scripts[name].other)
  2656. for (domain of scripts[name].other) if (!(domain in scripts))
  2657. scripts[domain] = scripts[name];
  2658. // look for current domain in the list and run appropriate code
  2659. domain = document.domain;
  2660. while (domain.indexOf('.') > -1)
  2661. {
  2662. if (domain in scripts)
  2663. {
  2664. if (typeof scripts[domain] === 'function')
  2665. {
  2666. document.addEventListener ('DOMContentLoaded', scripts[domain], false);
  2667. break;
  2668. }
  2669. for (name in scripts[domain])
  2670. switch(name)
  2671. {
  2672. case 'other':
  2673. break;
  2674. case 'now':
  2675. scripts[domain][name]();
  2676. break;
  2677. case 'load':
  2678. window.addEventListener('load', scripts[domain][name], false);
  2679. break;
  2680. case 'dom':
  2681. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2682. break;
  2683. default:
  2684. document.addEventListener (name, scripts[domain][name], false);
  2685. }
  2686. }
  2687. domain = domain.slice(domain.indexOf('.') + 1);
  2688. }
  2689. })();