RU AdList JS Fixes

try to take over the world!

目前為 2017-09-11 提交的版本,檢視 最新版本

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