RU AdList JS Fixes

try to take over the world!

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

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