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