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