RU AdList JS Fixes

try to take over the world!

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

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