RU AdList JS Fixes

try to take over the world!

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

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