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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址