RU AdList JS Fixes

try to take over the world!

当前为 2017-07-25 提交的版本,查看 最新版本

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

QingJ © 2025

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