RU AdList JS Fixes

try to take over the world!

当前为 2017-08-04 提交的版本,查看 最新版本

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