RU AdList JS Fixes

try to take over the world!

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

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