RU AdList JS Fixes

try to take over the world!

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

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