RU AdList JS Fixes

try to take over the world!

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

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