RU AdList JS Fixes

try to take over the world!

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

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