RU AdList JS Fixes

try to take over the world!

目前為 2017-07-22 提交的版本,檢視 最新版本

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