RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

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