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