RU AdList JS Fixes

try to take over the world!

目前為 2017-08-18 提交的版本,檢視 最新版本

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