RU AdList JS Fixes

try to take over the world!

目前為 2017-07-16 提交的版本,檢視 最新版本

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