RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20170829.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. // @run-at document-start
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17. let win = (unsafeWindow || window),
  18. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  19. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  20. isChrome = !!window.chrome && !!window.chrome.webstore,
  21. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  22. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  23. isFirefox = typeof InstallTrigger !== 'undefined',
  24. inIFrame = (win.self !== win.top),
  25. _getAttribute = Element.prototype.getAttribute,
  26. _setAttribute = Element.prototype.setAttribute,
  27. _de = document.documentElement,
  28. _appendChild = Document.prototype.appendChild.bind(_de),
  29. _removeChild = Document.prototype.removeChild.bind(_de),
  30. _createElement = Document.prototype.createElement.bind(document);
  31.  
  32. if (isFirefox && // Exit on image pages in Fx
  33. document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  34. return;
  35.  
  36. // dTree 2.05 in some cases replaces Node object before my script kicks in :(
  37. if (!Node.prototype)
  38. {
  39. let ifr = _createElement('iframe');
  40. _appendChild(ifr);
  41. try {
  42. window.Node = ifr.contentWindow.Node;
  43. console.log('Node object restored. -_-');
  44. } catch(e) {
  45. console.log('Unable to restore Node object.', e);
  46. }
  47. _removeChild(ifr);
  48. }
  49.  
  50. // NodeList iterator polyfill (mostly for Safari)
  51. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  52. if (!NodeList.prototype[Symbol.iterator]) {
  53. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  54. }
  55.  
  56. // Options
  57. let opts = {
  58. 'useWSIFunc': useWSI
  59. };
  60.  
  61. {
  62. let optsCall = function(callback)
  63. {
  64. // Register event listener
  65. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  66. cb = callback.func.bind(callback.name);
  67. window.addEventListener(key, cb, false);
  68. // Generate and dispatch synthetic event
  69. let ev = document.createEvent("HTMLEvents");
  70. ev.initEvent(key, true, false);
  71. window.dispatchEvent(ev);
  72. // Remove listener
  73. window.removeEventListener(key, cb, false);
  74. };
  75.  
  76. let initOptsHandler = function()
  77. {
  78. /*jshint validthis:true */
  79. opts[this] = GM_getValue(this, true);
  80. if (opts[this])
  81. opts[this+'Func']();
  82. };
  83.  
  84. optsCall({
  85. func: initOptsHandler,
  86. name: 'useWSI'
  87. });
  88.  
  89. // show options page
  90. let openOptions = function()
  91. {
  92. let ovl = _createElement('div'),
  93. inner = _createElement('div');
  94. ovl.style = (
  95. 'position: fixed;'+
  96. 'top:0; left:0;'+
  97. 'bottom: 0; right: 0;'+
  98. 'background: rgba(0,0,0,0.85);'+
  99. 'z-index: 2147483647;'+
  100. 'padding: 5em'
  101. );
  102. inner.style = (
  103. 'background: whitesmoke;'+
  104. 'font-size: 10pt;'+
  105. 'color: black;'+
  106. 'padding: 1em'
  107. );
  108. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  109. inner.appendChild(_createElement('br'));
  110. inner.appendChild(_createElement('br'));
  111. ovl.addEventListener(
  112. 'click', function(e)
  113. {
  114. if (e.target === ovl) {
  115. ovl.parentNode.removeChild(ovl);
  116. e.preventDefault();
  117. }
  118. e.stopPropagation();
  119. }, false
  120. );
  121. // append checkbox with label function
  122. function addCheckbox(optName, optLabel)
  123. {
  124. let c = _createElement('input'),
  125. l = _createElement('label');
  126. c.type = 'checkbox';
  127. c.id = optName;
  128. optsCall({
  129. func: function()
  130. {
  131. c.checked = GM_getValue(this);
  132. },
  133. name: optName
  134. });
  135. c.addEventListener(
  136. 'click', function(e)
  137. {
  138. optsCall({
  139. func:function(){
  140. GM_setValue(this, e.target.checked);
  141. opts[this] = e.target.checked;
  142. },
  143. name:optName
  144. });
  145. }, true
  146. );
  147. l.textContent = optLabel;
  148. l.setAttribute('for', optName);
  149. inner.appendChild(c);
  150. inner.appendChild(l);
  151. inner.appendChild(_createElement('br'));
  152. }
  153. // append checkboxes
  154. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  155. document.body.appendChild(ovl);
  156. ovl.appendChild(inner);
  157. };
  158.  
  159. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  160. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  161. document.addEventListener(
  162. 'keydown', function(e)
  163. {
  164. if ((e.code === opKey[opPos] || e.location) &&
  165. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  166. {
  167. opPos += e.location ? 0 : 1;
  168. e.stopPropagation();
  169. e.preventDefault();
  170. } else {
  171. opPos = 0;
  172. }
  173. if (opPos === opKey.length)
  174. {
  175. opPos = 0;
  176. openOptions();
  177. }
  178. }, false
  179. );
  180. }
  181.  
  182. // Special wrapper script to run scripts designed to override standard DOM functions
  183. // In Firefox appends supplied script to a page to make it run in page context and let
  184. // page content access overridden functions. In other browsers just run it as-is.
  185. function scriptLander(func, prepend)
  186. {
  187. if (!isFirefox)
  188. {
  189. func();
  190. return;
  191. }
  192. let script = _createElement('script');
  193. let inline = ['string', 'function'];
  194. script.textContent = '!function(){let win=window;' + (
  195. inline.includes(typeof prepend) && prepend ||
  196. prepend instanceof Array && prepend.join(';') || ''
  197. ) + ';!' + func + '();}();';
  198. _appendChild(script);
  199. _removeChild(script);
  200. }
  201.  
  202. function nullTools(log) {
  203. /*jshint validthis:true */
  204. let nt = this;
  205. function trace() { if (log) console.trace.apply(this, arguments); }
  206.  
  207. nt.define = function(obj, prop, val)
  208. {
  209. Object.defineProperty(
  210. obj, prop, {
  211. get: () => (trace('get', prop, 'of', obj, 'which is', val), val),
  212. set: (v) => (trace('set', prop, 'of', obj, 'to', v), v),
  213. enumerable: true
  214. }
  215. );
  216. };
  217. nt.proxy = function(obj)
  218. {
  219. return new Proxy(
  220. obj, {
  221. get: (t, p) => (trace('get', p, 'of', t, 'which is', t[p]), t[p]),
  222. set: (t, p, v) => (trace('set', p, 'of', t, 'to', v), v)
  223. }
  224. );
  225. };
  226. nt.func = (val) => () => (trace('call func, return', val), val);
  227. }
  228.  
  229. // Fake objects of advertisement networks to break their workflow
  230. scriptLander(
  231. function()
  232. {
  233. let l = window.location;
  234. if (/^([^.]+\.)*?google\./i.test(l.host) ||
  235. // Google likes to define odd global variables like Ya
  236. (/^([^.]+\.)*?yandex\./i.test(l.host) &&
  237. /^\/(search|images|video)/.test(l.pathname)) ||
  238. // Also, Yandex uses their Ya object for a lot of things on their pages and
  239. // wrapping it may cause problems. It's better to skip it in some cases.
  240. /[./](github\.io|grimtools\.com)$/i.test(l.host))
  241. return;
  242.  
  243. let nt = new nullTools();
  244. // Yandex API (ADBTools, Metrika)
  245. let Ya = {};
  246. nt.define(Ya, 'ADBTools', function(){
  247. for (let name of ['loadContext', 'testAdbStyle'])
  248. this[name] = nt.func(null);
  249. this.getCurrentState = nt.func(true);
  250. return nt.proxy(this);
  251. });
  252. nt.define(Ya, 'adfoxCode', nt.proxy({
  253. create: nt.func(null),
  254. createAdaptive: 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. // cleanup
  1066. let news = {}, to_remove = [];
  1067. for (let node of document.querySelectorAll('.profit'))
  1068. node.removeAttribute('data-bem');
  1069. for (let node of document.querySelectorAll('.profit .story'))
  1070. if (news[node.className])
  1071. ;//to_remove.push(node);
  1072. else
  1073. news[node.className] = true;
  1074. for (let node of to_remove)
  1075. remove(node);
  1076. }
  1077. // Music ads
  1078. function removeMusicAds()
  1079. {
  1080. for (let node of document.querySelectorAll('.ads-block'))
  1081. remove(node);
  1082. }
  1083. // Mail ads
  1084. function removeMailAds()
  1085. {
  1086. let slice = Array.prototype.slice,
  1087. nodes = slice.call(document.querySelectorAll('.ns-view-folders')),
  1088. node, len, cls;
  1089.  
  1090. for (node of nodes)
  1091. if (!len || len > node.classList.length)
  1092. len = node.classList.length;
  1093.  
  1094. node = nodes.pop();
  1095. while (node)
  1096. {
  1097. if (node.classList.length > len)
  1098. for (cls of slice.call(node.classList))
  1099. if (cls.indexOf('-') === -1)
  1100. {
  1101. remove(node);
  1102. break;
  1103. }
  1104. node = nodes.pop();
  1105. }
  1106. }
  1107. // News fixes
  1108. function removePageAdsClass()
  1109. {
  1110. if (document.body.classList.contains("b-page_ads_yes"))
  1111. {
  1112. document.body.classList.remove("b-page_ads_yes");
  1113. console.log('Page ads class removed.');
  1114. }
  1115. }
  1116. // Function to attach an observer to monitor dynamic changes on the page
  1117. function pageUpdateObserver(func, obj, params) {
  1118. if (obj)
  1119. (new MutationObserver(func))
  1120. .observe(obj, (params || { childList:true, subtree:true }));
  1121. }
  1122.  
  1123. if (win.location.hostname.search(/^mail\./i) === 0) {
  1124. pageUpdateObserver(
  1125. function(ms, o)
  1126. {
  1127. let aside = document.querySelector('.mail-Layout-Aside');
  1128. if (aside) {
  1129. o.disconnect();
  1130. pageUpdateObserver(removeMailAds, aside);
  1131. }
  1132. }, document.body
  1133. );
  1134. removeMailAds();
  1135. } else if (win.location.hostname.search(/^music\./i) === 0) {
  1136. pageUpdateObserver(removeMusicAds, document.querySelector('.sidebar'));
  1137. removeMusicAds();
  1138. } else if (win.location.hostname.search(/^news\./i) === 0) {
  1139. pageUpdateObserver(removeNewsAds, document.body);
  1140. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1141. removeNewsAds();
  1142. removePageAdsClass();
  1143. } else {
  1144. pageUpdateObserver(removeSearchAds, document.querySelector('.main__content'));
  1145. removeSearchAds();
  1146. }
  1147. }
  1148. );
  1149.  
  1150. // Yandex Link Tracking
  1151. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1152. {
  1153. let fakeRoot = {
  1154. firstChild: null,
  1155. appendChild: ()=>null,
  1156. querySelector: ()=>null,
  1157. querySelectorAll: ()=>null
  1158. };
  1159. Element.prototype.createShadowRoot = () => fakeRoot;
  1160. Object.defineProperty(Element.prototype, "shadowRoot", {
  1161. value: fakeRoot,
  1162. enumerable: true,
  1163. configurable: false
  1164. });
  1165. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1166. let selectors = (
  1167. 'A[onmousedown*="/jsredir"],'+
  1168. 'A[data-vdir-href],'+
  1169. 'A[data-counter]'
  1170. );
  1171. let removeTrackingAttributes = function(link)
  1172. {
  1173. link.removeAttribute('onmousedown');
  1174. if (link.hasAttribute('data-vdir-href')) {
  1175. link.removeAttribute('data-vdir-href');
  1176. link.removeAttribute('data-orig-href');
  1177. }
  1178. if (link.hasAttribute('data-counter')) {
  1179. link.removeAttribute('data-counter');
  1180. link.removeAttribute('data-bem');
  1181. }
  1182. };
  1183. let removeTracking = function(scope)
  1184. {
  1185. for (let link of scope.querySelectorAll(selectors))
  1186. removeTrackingAttributes(link);
  1187. };
  1188. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1189. (new MutationObserver(
  1190. function(ms)
  1191. {
  1192. let m, node;
  1193. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1194. if (node.tagName === 'A' && node.matches(selectors)) {
  1195. removeTrackingAttributes(node);
  1196. } else {
  1197. removeTracking(node);
  1198. }
  1199. }
  1200. )).observe(_de, { childList: true, subtree: true });
  1201.  
  1202. //skip fixes for other sites
  1203. return;
  1204. }
  1205.  
  1206. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1207. document.addEventListener(
  1208. 'DOMContentLoaded', function()
  1209. {//createPlayer();
  1210. function log (e) {
  1211. console.log('Player FIX: Detected', e, 'player in', win.location.href);
  1212. }
  1213. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1214. {
  1215. log('Moonwalk');
  1216. if (win.adv_enabled)
  1217. win.adv_enabled = false;
  1218. win.condition_detected = false;
  1219. if (win.MXoverrollCallback)
  1220. document.addEventListener(
  1221. 'click', function catcher(e)
  1222. {
  1223. e.stopPropagation();
  1224. win.MXoverrollCallback.call(window);
  1225. document.removeEventListener('click', catcher, true);
  1226. }, true
  1227. );
  1228. }
  1229. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1230. {
  1231. log('HDGo');
  1232. document.body.onclick = null;
  1233. let tmp = document.querySelector('#swtf');
  1234. if (tmp)
  1235. tmp.style.display = 'none';
  1236. if (win.banner_second !== undefined)
  1237. win.banner_second = 0;
  1238. if (win.$banner_ads !== undefined)
  1239. win.$banner_ads = false;
  1240. if (win.$new_ads !== undefined)
  1241. win.$new_ads = false;
  1242. if (win.createCookie !== undefined)
  1243. win.createCookie('popup', 'true', '999');
  1244. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1245. win.canRunAds = true;
  1246. }
  1247. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1248. {
  1249. log('Kodik');
  1250. let tmp = document.querySelector('.play_button');
  1251. if (tmp)
  1252. tmp.onclick = win.MXoverrollCallback.bind(window);
  1253. win.IsAdBlock = false;
  1254. }
  1255. else if (win.getnextepisode && win.uppodEvent)
  1256. {
  1257. log('Share-Serials.net');
  1258. scriptLander(
  1259. function()
  1260. {
  1261. let _setInterval = win.setInterval,
  1262. _setTimeout = win.setTimeout;
  1263. win.setInterval = function(func)
  1264. {
  1265. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1266. {
  1267. let intv = _setInterval.call(
  1268. this, function()
  1269. {
  1270. _setTimeout.call(
  1271. this, function(intv)
  1272. {
  1273. clearInterval(intv);
  1274. let timer = document.querySelector('#timer');
  1275. if (timer)
  1276. timer.click();
  1277. }, 100, intv);
  1278. func.call(this);
  1279. }, 5
  1280. );
  1281.  
  1282. return intv;
  1283. }
  1284. return _setInterval.apply(this, arguments);
  1285. };
  1286. win.setTimeout = function(func) {
  1287. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1288. {
  1289. return _setTimeout.call(this, func, 0);
  1290. }
  1291. return _setTimeout.apply(this, arguments);
  1292. };
  1293. }
  1294. );
  1295. }
  1296. }, false
  1297. );
  1298.  
  1299. // piguiqproxy.com circumvention prevention
  1300. scriptLander(
  1301. function()
  1302. {
  1303. let _open = XMLHttpRequest.prototype.open;
  1304. let blacklist = /[/.@]piguiqproxy\.com[:/]/i;
  1305. XMLHttpRequest.prototype.open = function(method, url)
  1306. {
  1307. if (method === 'GET' && blacklist.test(url))
  1308. {
  1309. this.send = () => null;
  1310. console.log('Blocked request: ', url);
  1311. return;
  1312. }
  1313. return _open.apply(this, arguments);
  1314. };
  1315. }
  1316. );
  1317.  
  1318. // === Helper functions ===
  1319.  
  1320. // function to search and remove nodes by content
  1321. // selector - standard CSS selector to define set of nodes to check
  1322. // words - regular expression to check content of the suspicious nodes
  1323. // params - object with multiple extra parameters:
  1324. // .log - display log in the console
  1325. // .hide - set display to none instead of removing from the page
  1326. // .parent - parent node to remove if content is found in the child node
  1327. // .siblings - number of simling nodes to remove (excluding text nodes)
  1328. let scRemove = (node) => node.parentNode.removeChild(node);
  1329. let scHide = function(node)
  1330. {
  1331. let style = _getAttribute.call(node, 'style') || '',
  1332. hide = ';display:none!important;';
  1333. if (style.indexOf(hide) < 0)
  1334. _setAttribute.call(node, 'style', style + hide);
  1335. };
  1336. function scissors (selector, words, scope, params)
  1337. {
  1338. if (params.log)
  1339. console.log('[s] starting with', selector, words, scope, JSON.stringify(params));
  1340. let remFunc = (params.hide ? scHide : scRemove),
  1341. iterFunc = (params.siblings > 0 ? 'nextSibling' : 'previousSibling'),
  1342. toRemove = [],
  1343. siblings;
  1344. for (let node of scope.querySelectorAll(selector))
  1345. {
  1346. if (params.log)
  1347. console.log('[s] found node', node);
  1348. if (params.parent)
  1349. {
  1350. while(node !== scope && !(node.matches(params.parent)))
  1351. node = node.parentNode;
  1352. if (params.log)
  1353. console.log('[s] moving to parent node', node);
  1354. if (node === scope)
  1355. {
  1356. if (params.log)
  1357. console.log('[s] reached scope node, nothing to remove here.');
  1358. break;
  1359. }
  1360. }
  1361. if (words.test(node.innerHTML) || !node.childNodes.length)
  1362. {
  1363. // drill up to the specified parent node if required
  1364. if (toRemove.indexOf(node) === -1)
  1365. {
  1366. if (params.log)
  1367. console.log('[s] adding node into list for removal');
  1368. toRemove.push(node);
  1369. // add multiple nodes if defined more than one sibling
  1370. siblings = Math.abs(params.siblings) || 0;
  1371. while (siblings)
  1372. {
  1373. node = node[iterFunc];
  1374. if (node.nodeType === Node.ELEMENT_NODE)
  1375. {
  1376. if (params.log)
  1377. console.log('[s] adding sibling node', node);
  1378. toRemove.push(node);
  1379. siblings -= 1; //count only element nodes
  1380. }
  1381. else if (!params.hide)
  1382. {
  1383. if (params.log)
  1384. console.log('[s] adding sibling node', node);
  1385. toRemove.push(node);
  1386. }
  1387. }
  1388. } else {
  1389. if (params.log)
  1390. console.log('[s] node already marked for removal');
  1391. }
  1392. } else {
  1393. if (params.log)
  1394. console.log('[s] word test failed, proceed to the next node');
  1395. }
  1396. }
  1397. if (params.log)
  1398. console.log('[s] proceeding with', (params.hide?'hide':'removal'), 'of', toRemove);
  1399. for (let node of toRemove)
  1400. remFunc(node);
  1401.  
  1402. return toRemove.length;
  1403. }
  1404.  
  1405. // function to perform multiple checks if ads inserted with a delay
  1406. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1407. // also does 1 extra check when a page completely loads
  1408. // selector and words - passed dow to scissors
  1409. // params - object with multiple extra parameters:
  1410. // .log - display log in the console
  1411. // .root - selector to narrow down scope to scan;
  1412. // .observe - if true then check will be performed continuously;
  1413. // Other parameters passed down to scissors.
  1414. function gardener(selector, words, params)
  1415. {
  1416. params = params || {};
  1417. if (params.log)
  1418. console.log('[g] starting with', selector, words, JSON.stringify(params));
  1419. let scope = document,
  1420. nonstop = false;
  1421. // narrow down scope to a specific element
  1422. if (params.root)
  1423. {
  1424. scope = scope.querySelector(params.root);
  1425. if (!scope) // exit if the root element is not present on the page
  1426. return 0;
  1427. if (params.log)
  1428. console.log('[g] scope', scope);
  1429. }
  1430. // add observe mode if required
  1431. if (params.observe)
  1432. {
  1433. if (typeof MutationObserver === 'function')
  1434. {
  1435. (new MutationObserver(
  1436. function(ms)
  1437. {
  1438. for (let m of ms) if (m.addedNodes.length)
  1439. scissors(selector, words, scope, params);
  1440. }
  1441. )).observe(scope, { childList:true, subtree: true });
  1442. if (params.log)
  1443. console.log('[g] observer enabled');
  1444. } else {
  1445. nonstop = true;
  1446. if (params.log)
  1447. console.log('[g] nonstop mode enabled');
  1448. }
  1449. }
  1450. // wait for a full page load to do one extra cut
  1451. win.addEventListener(
  1452. 'load', function()
  1453. {
  1454. if (params.log)
  1455. console.log('[g] onload cleanup');
  1456. scissors(selector, words, scope, params);
  1457. }
  1458. );
  1459. // do multiple cuts during page load until ads removed
  1460. function cut(sci, s, w, sc, p, i)
  1461. {
  1462. if (i > 0)
  1463. i -= 1;
  1464. if (i && !sci(s, w, sc, p))
  1465. setTimeout(cut, 100, sci, s, w, sc, p, i);
  1466. }
  1467. cut(scissors, selector, words, scope, params, (nonstop ? -1 : 30));
  1468. }
  1469.  
  1470. // wrap popular methods to open a new tab to catch specific behaviours
  1471. function createWindowOpenWrapper(openFunc, onClickFunc)
  1472. {
  1473. let _createElement = Document.prototype.createElement,
  1474. _appendChild = Element.prototype.appendChild;
  1475.  
  1476. function redefineOpen(obj)
  1477. {
  1478. Object.defineProperty(obj, 'open', {
  1479. get: () => openFunc,
  1480. set: (val) => val,
  1481. enumerable: true
  1482. });
  1483. }
  1484. redefineOpen(win);
  1485.  
  1486. Document.prototype.createElement = function createElement(name)
  1487. {
  1488. let el = _createElement.apply(this, arguments);
  1489. // click-dispatch check for Google Chrome and similar browsers
  1490. if (el instanceof HTMLAnchorElement)
  1491. el.addEventListener(
  1492. 'click', onClickFunc, false
  1493. );
  1494. // redefine window.open in first-party frames
  1495. if (el instanceof HTMLIFrameElement)
  1496. el.addEventListener(
  1497. 'load', function(e)
  1498. {
  1499. try {
  1500. redefineOpen(e.target.contentWindow);
  1501. } catch(ignore) {}
  1502. }, false
  1503. );
  1504. return el;
  1505. };
  1506.  
  1507. // wrap window.open in newly added first-party frames
  1508. Element.prototype.appendChild = function appendChild()
  1509. {
  1510. let el = _appendChild.apply(this, arguments);
  1511. if (el instanceof HTMLIFrameElement) {
  1512. try {
  1513. redefineOpen(el.contentWindow);
  1514. } catch(ignore) {}
  1515. }
  1516. return el;
  1517. };
  1518. }
  1519.  
  1520. // Function to catch and block various methods to open a new window with 3rd-party content.
  1521. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1522. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1523. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1524. // node or simply a link with piece of javascript code in the HREF attribute.
  1525. function preventPopups()
  1526. {
  1527. if (inIFrame)
  1528. {
  1529. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1530. return;
  1531. }
  1532.  
  1533. scriptLander(
  1534. function()
  1535. {
  1536. function open()
  1537. {
  1538. '[native code]';
  1539. console.log('Site attempted to open a new window', arguments);
  1540. return {
  1541. document: {
  1542. write: () => {},
  1543. writeln: () => {}
  1544. }
  1545. };
  1546. }
  1547.  
  1548. function clickHandler(e)
  1549. {
  1550. let link = e.target;
  1551. if (!link.parentNode || !e.isTrusted ||
  1552. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  1553. {
  1554. e.preventDefault();
  1555. console.log('Blocked suspicious click event', e, 'on', e.target);
  1556. }
  1557. }
  1558.  
  1559. createWindowOpenWrapper(open, clickHandler);
  1560.  
  1561. console.log('Popup prevention enabled.');
  1562. }, createWindowOpenWrapper
  1563. );
  1564. }
  1565.  
  1566. // Helper function to close background tab if site opens itself in a new tab and then
  1567. // loads a 3rd-party page in the background one (thus performing background redirect).
  1568. function preventPopunders()
  1569. {
  1570. // create "close_me" event to call high-level window.close()
  1571. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1572. let callClose = () => (console.log('close call'), window.close());
  1573. window.addEventListener(eventName, callClose, true);
  1574.  
  1575. scriptLander(
  1576. function()
  1577. {
  1578. let _open = window.open,
  1579. parseURL = document.createElement('A');
  1580. // get host of a provided URL with help of an anchor object
  1581. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1582. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1583. // site went to a new tab and attempts to unload
  1584. // call for high-level close through event
  1585. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1586. // check is URL local or goes to different site
  1587. function isLocal(url)
  1588. {
  1589. let loc = window.location;
  1590. if (url === loc.pathname || url === loc.href)
  1591. return true; // URL points to current pathname or full address
  1592. let host = getHost(url),
  1593. site = loc.host;
  1594. if (host === '')
  1595. return false; // URLs with unusual protocol may have empty 'host'
  1596. if (host.length > site.length)
  1597. [site, host] = [host, site];
  1598. return site.includes(host, site.length - host.length);
  1599. }
  1600.  
  1601. function open(url)
  1602. {
  1603. '[native code]';
  1604. if (url && isLocal(url))
  1605. window.addEventListener('unload', closeWindow, true);
  1606. /*jshint validthis:true */
  1607. return _open.apply(this, arguments);
  1608. }
  1609.  
  1610. function clickHandler(e)
  1611. {
  1612. if (!e.target.parentNode || !e.isTrusted)
  1613. window.addEventListener('unload', closeWindow, true);
  1614. }
  1615.  
  1616. createWindowOpenWrapper(open, clickHandler);
  1617.  
  1618. console.log("Background redirect prevention enabled.");
  1619. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1620. );
  1621. }
  1622.  
  1623. // Mix between check for popups and popunders
  1624. // Significantly more agressive than both and can't be used as universal solution
  1625. function preventPopMix()
  1626. {
  1627. if (inIFrame)
  1628. {
  1629. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1630. return;
  1631. }
  1632.  
  1633. // create "close_me" event to call high-level window.close()
  1634. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1635. let callClose = () => (console.log('close call'), window.close());
  1636. window.addEventListener(eventName, callClose, true);
  1637.  
  1638. scriptLander(
  1639. function()
  1640. {
  1641. let _open = window.open,
  1642. parseURL = document.createElement('A');
  1643. // get host of a provided URL with help of an anchor object
  1644. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1645. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1646. // site went to a new tab and attempts to unload
  1647. // call for high-level close through event
  1648. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  1649. // check is URL local or goes to different site
  1650. function isLocal(url)
  1651. {
  1652. let loc = window.location;
  1653. if (url === loc.pathname || url === loc.href)
  1654. return true; // URL points to current pathname or full address
  1655. let host = getHost(url),
  1656. site = loc.host;
  1657. if (host === '')
  1658. return false; // URLs with unusual protocol may have empty 'host'
  1659. if (host.length > site.length)
  1660. [site, host] = [host, site];
  1661. return site.includes(host, site.length - host.length);
  1662. }
  1663.  
  1664. // add check for redirect for 5 seconds, then disable it
  1665. function checkRedirect()
  1666. {
  1667. window.addEventListener('unload', closeWindow, true);
  1668. setTimeout(closeWindow=>window.removeEventListener('unload', closeWindow, true), 5000, closeWindow);
  1669. }
  1670.  
  1671. function open(url, name)
  1672. {
  1673. '[native code]';
  1674. if (url && isLocal(url) && (!name || name === '_blank'))
  1675. {
  1676. console.log('Suspicious local new window', arguments);
  1677. checkRedirect();
  1678. /*jshint validthis:true */
  1679. return _open.apply(this, arguments);
  1680. }
  1681. console.log('Blocked attempt to open a new window', arguments);
  1682. return {
  1683. document: {
  1684. write: () => {},
  1685. writeln: () => {}
  1686. }
  1687. };
  1688. }
  1689.  
  1690. function clickHandler(e)
  1691. {
  1692. let link = e.target,
  1693. url = link.href||'';
  1694. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  1695. {
  1696. console.log('Link', link, 'were created dinamically, but looks fine.');
  1697. return true;
  1698. }
  1699. if (isLocal(url) && link.target === '_blank')
  1700. {
  1701. console.log('Suspicious local link', link);
  1702. checkRedirect();
  1703. return;
  1704. }
  1705. console.log('Blocked suspicious click on a link', link);
  1706. e.stopPropagation();
  1707. e.preventDefault();
  1708. }
  1709.  
  1710. createWindowOpenWrapper(open, clickHandler);
  1711.  
  1712. console.log("Mixed popups prevention enabled.");
  1713. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1714. );
  1715. }
  1716. // External listener for case when site known to open popups were loaded in iframe
  1717. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1718. // Some sites replace frame's window.location with data-url to run in clean context
  1719. if (!inIFrame)
  1720. {
  1721. window.addEventListener(
  1722. 'message', function(e)
  1723. {
  1724. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1725. return;
  1726. let src = e.data.href;
  1727. for (let frame of document.querySelectorAll('iframe'))
  1728. if (frame.contentWindow === e.source)
  1729. {
  1730. if (frame.hasAttribute('sandbox'))
  1731. {
  1732. if (!frame.sandbox.has('allow-popups'))
  1733. return; // exit frame since it's already sandboxed and popups are blocked
  1734. // remove allow-popups if frame already sandboxed
  1735. frame.sandbox.remove('allow-popups');
  1736. } else {
  1737. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1738. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1739. // but to apply content must be reloaded and this script will re-apply it in the result
  1740. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1741. }
  1742. console.log('Disallowed popups from iframe', frame);
  1743.  
  1744. // reload frame content to apply restrictions
  1745. if (!src) {
  1746. src = frame.src;
  1747. console.log('Unable to get current iframe location, reloading from src', src);
  1748. } else
  1749. console.log('Reloading iframe with URL', src);
  1750. frame.src = 'about:blank';
  1751. frame.src = src;
  1752. }
  1753. }, false
  1754. );
  1755. }
  1756.  
  1757. // === Scripts for specific domains ===
  1758.  
  1759. let scripts = {};
  1760. // prevent popups and redirects block
  1761. // Popups
  1762. scripts.preventPopups = {
  1763. other: [
  1764. 'biqle.ru',
  1765. 'chaturbate.com',
  1766. 'dfiles.ru',
  1767. 'hentaiz.org',
  1768. 'mirrorcreator.com',
  1769. 'online-multy.ru',
  1770. 'radikal.ru',
  1771. 'seedoff.cc', 'seedoff.tv',
  1772. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1773. 'unionpeer.com',
  1774. 'zippyshare.com'
  1775. ],
  1776. now: preventPopups
  1777. };
  1778. // Popunders (background redirect)
  1779. scripts.preventPopunders = {
  1780. other: [
  1781. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1782. 'perfectgirls.net'
  1783. ],
  1784. now: preventPopunders
  1785. };
  1786. // PopMix (both types of popups encountered on site)
  1787. scripts.preventPopMix = {
  1788. other: [
  1789. 'openload.co',
  1790. 'turbobit.net'
  1791. ],
  1792. now: preventPopMix
  1793. };
  1794.  
  1795. // other
  1796. scripts['2picsun.ru'] = {
  1797. other: [
  1798. 'pics2sun.ru', '3pics-img.ru'
  1799. ],
  1800. now: function() {
  1801. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  1802. }
  1803. };
  1804.  
  1805. scripts['4pda.ru'] = {
  1806. now: function()
  1807. {
  1808. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  1809. let hStyle,
  1810. isForum = document.location.href.search('/forum/') !== -1,
  1811. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  1812. afterClean = () => remove(hStyle);
  1813.  
  1814. function beforeClean()
  1815. {
  1816. // attach styles before document displayed
  1817. hStyle = createStyle([
  1818. 'html { overflow-y: scroll }',
  1819. 'section[id] {'+(
  1820. 'position: absolute;'+
  1821. 'width: 100%'
  1822. )+'}',
  1823. 'article + aside * { display: none !important }',
  1824. '#header + div:after {'+(
  1825. 'content: "";'+
  1826. 'position: fixed;'+
  1827. 'top: 0;'+
  1828. 'left: 0;'+
  1829. 'width: 100%;'+
  1830. 'height: 100%;'+
  1831. 'background-color: #E6E7E9'
  1832. )+'}',
  1833. // http://codepen.io/Beaugust/pen/DByiE
  1834. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  1835. 'article + aside:after {'+(
  1836. 'content: "";'+
  1837. 'position: absolute;'+
  1838. 'width: 150px;'+
  1839. 'height: 150px;'+
  1840. 'top: 150px;'+
  1841. 'left: 50%;'+
  1842. 'margin-top: -75px;'+
  1843. 'margin-left: -75px;'+
  1844. 'box-sizing: border-box;'+
  1845. 'border-radius: 100%;'+
  1846. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  1847. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  1848. 'animation: spin 2s infinite linear'
  1849. )+'}'
  1850. ], {id:'ubrHider'}, true);
  1851.  
  1852. // display content of a page if time to load a page is more than 2 seconds to avoid
  1853. // blocking access to a page if it is loading for too long or stuck in a loading state
  1854. setTimeout(2000, afterClean);
  1855. }
  1856.  
  1857. createStyle([
  1858. '#nav .use-ad { display: block !important }',
  1859. 'article:not(.post) + article:not(#id),'+
  1860. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  1861. ]);
  1862.  
  1863. if (!isForum)
  1864. beforeClean();
  1865.  
  1866. // save links to non-overridden functions to use later
  1867. let protectedElems;
  1868. // protect/hide changed attributes in case site attempt to restore them
  1869. function styleProtector(eventMode)
  1870. {
  1871. let _toLowerCase = String.prototype.toLowerCase,
  1872. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  1873. protectedElems = new WeakMap();
  1874. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  1875. {
  1876. let originalFunction = element.prototype[functionName];
  1877. element.prototype[functionName] = function wrapper()
  1878. {
  1879. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  1880. return returnIfProtected(this, arguments);
  1881. return originalFunction.apply(this, arguments);
  1882. };
  1883. }
  1884. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  1885. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  1886. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  1887. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  1888. if (!eventMode)
  1889. return protectedElems;
  1890. else
  1891. {
  1892. let e = document.createEvent('Event');
  1893. e.initEvent('protoOverride', false, false);
  1894. window.protectedElems = protectedElems;
  1895. window.dispatchEvent(e);
  1896. }
  1897. }
  1898. if (!isFirefox)
  1899. protectedElems = styleProtector(false);
  1900. else
  1901. {
  1902. let script = document.createElement('script');
  1903. script.textContent = '(' + styleProtector.toString() + ')(true);';
  1904. window.addEventListener(
  1905. 'protoOverride', function protoOverrideCallback(e)
  1906. {
  1907. if (win.protectedElems) {
  1908. protectedElems = win.protectedElems;
  1909. delete win.protectedElems;
  1910. }
  1911. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  1912. }, true
  1913. );
  1914. _appendChild(script);
  1915. _removeChild(script);
  1916. }
  1917.  
  1918. // clean a page
  1919. window.addEventListener(
  1920. 'DOMContentLoaded', function()
  1921. {
  1922. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  1923. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  1924.  
  1925. if (isForum)
  1926. {
  1927. let si = document.querySelector('#logostrip');
  1928. if (si)
  1929. remove(si.parentNode.nextSibling);
  1930. }
  1931.  
  1932. if (document.location.href.search('/forum/dl/') !== -1) {
  1933. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  1934. ';background-color:black!important');
  1935. for (let itm of document.querySelectorAll('body>div'))
  1936. if (!itm.querySelector('.dw-fdwlink'))
  1937. remove(itm);
  1938. }
  1939.  
  1940. if (isForum) // Do not continue if it's a forum
  1941. return;
  1942.  
  1943. {
  1944. let si = document.querySelector('#header');
  1945. if (si)
  1946. {
  1947. let rem = si.previousSibling;
  1948. while (rem)
  1949. {
  1950. si = rem.previousSibling;
  1951. remove(rem);
  1952. rem = si;
  1953. }
  1954. }
  1955. }
  1956.  
  1957. for (let itm of document.querySelectorAll('#nav li[class]'))
  1958. if (itm && itm.querySelector('a[href^="/tag/"]'))
  1959. remove(itm);
  1960.  
  1961. let style, result,
  1962. fakeStyles = new WeakMap(),
  1963. styleProxy = {
  1964. get: function(target, prop)
  1965. {
  1966. let fakeStyle = fakeStyles.get(target);
  1967. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  1968. },
  1969. set: function(target, prop, value)
  1970. {
  1971. let fakeStyle = fakeStyles.get(target);
  1972. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  1973. return value;
  1974. }
  1975. };
  1976. for (let itm of document.querySelectorAll('DIV, A'))
  1977. {
  1978. if (itm.tagName ==='DIV' &&
  1979. itm.offsetWidth > 0.95 * width() &&
  1980. itm.offsetHeight > 0.85 * height())
  1981. {
  1982. style = window.getComputedStyle(itm, null);
  1983. result = [];
  1984.  
  1985. if (style.backgroundImage !== 'none')
  1986. result.push('background-image:none!important');
  1987.  
  1988. if (style.backgroundColor !== 'transparent' &&
  1989. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  1990. result.push('background-color:transparent!important');
  1991.  
  1992. if (result.length)
  1993. {
  1994. if (itm.getAttribute('style'))
  1995. result.unshift(itm.getAttribute('style'));
  1996.  
  1997. fakeStyles.set(itm.style, {
  1998. 'backgroundImage': itm.style.backgroundImage,
  1999. 'backgroundColor': itm.style.backgroundColor
  2000. });
  2001.  
  2002. try {
  2003. Object.defineProperty(itm, 'style', {
  2004. value: new Proxy(itm.style, styleProxy),
  2005. enumerable: true
  2006. });
  2007. } catch (e) {
  2008. console.log('Unable to protect style property.', e);
  2009. }
  2010.  
  2011. if (protectedElems)
  2012. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2013.  
  2014. _setAttribute.call(itm, 'style', result.join(';'));
  2015. }
  2016. }
  2017. if (itm.tagName ==='A' &&
  2018. (itm.offsetWidth > 0.95 * width() ||
  2019. itm.offsetHeight > 0.85 * height()))
  2020. {
  2021. if (protectedElems)
  2022. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2023.  
  2024. _setAttribute.call(itm, 'style', 'display:none!important');
  2025. }
  2026. }
  2027.  
  2028. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2029. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2030. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2031. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2032. remove(itm);
  2033.  
  2034. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2035.  
  2036. // display content of the page
  2037. afterClean();
  2038. }
  2039. );
  2040. }
  2041. };
  2042.  
  2043. scripts['allmovie.pro'] = {
  2044. other: ['rufilmtv.org'],
  2045. dom: function()
  2046. {
  2047. // pretend to be Android to make site use different played for ads
  2048. if (isSafari)
  2049. return;
  2050. Object.defineProperty(navigator, 'userAgent', {
  2051. 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'; },
  2052. enumerable: true
  2053. });
  2054. }
  2055. };
  2056.  
  2057. scripts['anidub-online.ru'] = {
  2058. other: ['online.anidub.com'],
  2059. dom: function()
  2060. {
  2061. if (win.ogonekstart1)
  2062. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2063. },
  2064. now: () => createStyle([
  2065. '.background {background: none!important;}',
  2066. '.background > script + div,'+
  2067. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2068. '{display:none!important}'
  2069. ])
  2070. };
  2071.  
  2072. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2073.  
  2074. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров/);
  2075.  
  2076. scripts['gidonline.club'] = {
  2077. now: () => createStyle('.tray > div[style] {display: none!important}')
  2078. };
  2079.  
  2080. scripts['hdgo.cc'] = {
  2081. other: ['46.30.43.38', 'couber.be'],
  2082. now: () => (new MutationObserver(
  2083. function(ms)
  2084. {
  2085. let m, node;
  2086. for (m of ms) for (node of m.addedNodes)
  2087. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  2088. node.removeAttribute('onerror');
  2089. }
  2090. )).observe(document.documentElement, { childList:true, subtree: true })
  2091. };
  2092.  
  2093. scripts['gismeteo.ru'] = {
  2094. other: ['gismeteo.ua'],
  2095. dom: () => gardener('div > a[target^="_"]', /Яндекс\.Директ/i, { root: 'body', observe: true, parent: 'div[class*="frame"]'})
  2096. };
  2097.  
  2098. scripts['hdrezka.me'] = {
  2099. now: function()
  2100. {
  2101. Object.defineProperty(win, 'fuckAdBlock', {
  2102. value: { onDetected: () => console.log('Pretending to be an ABP detector.') },
  2103. enumerable: true
  2104. });
  2105. Object.defineProperty(win, 'ab', {
  2106. value: false,
  2107. enumerable: true
  2108. });
  2109. },
  2110. dom: () => gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i)
  2111. };
  2112.  
  2113. scripts['imageban.ru'] = {
  2114. now: preventPopunders,
  2115. dom: () => win.addEventListener(
  2116. 'unload', function()
  2117. {
  2118. window.location.hash = 'x'+Math.random().toString(36).substr(2);
  2119. }, true
  2120. )
  2121. };
  2122.  
  2123. scripts['mail.ru'] = {
  2124. now: function()
  2125. {
  2126. // Trick to prevent mail.ru from removing 3rd-party styles
  2127. scriptLander(
  2128. () => Object.defineProperty(Object.prototype, 'restoreVisibility', {
  2129. get: () => (() => null),
  2130. set: () => null
  2131. })
  2132. );
  2133. /* Experimental code, disabled for end users for now
  2134. // Ads removal on e.mail.ru
  2135. if (window.location.host === 'e.mail.ru')
  2136. {
  2137. let selector = (
  2138. '.b-datalist div[class]:not([id]) > div[class]:not([class*="js-"]),'+
  2139. '.b-letter div[class]:not([id]) > div[class]:not([class*="js-"]):not([class*="drop"]):not([class*="letter"]):not([style]):not([id]),'+
  2140. 'div[id]:not([class]) > div[id][class]:not([class*="js-"]):not([class*="drop"]):not([style])'
  2141. );
  2142. let janitor = function(nodes)
  2143. {
  2144. let color;
  2145. for (let node of nodes)
  2146. {
  2147. if (node.nodeType !== Node.ELEMENT_NODE)
  2148. continue;
  2149. color = window.getComputedStyle(node).backgroundColor;
  2150. if (/^rgb\(/.test(color) && color !== 'rgb(255, 255, 255)')
  2151. {
  2152. node.style.display = 'none';
  2153. console.log('Hide node:', node);
  2154. }
  2155. }
  2156. };
  2157. janitor(document.querySelectorAll(selector));
  2158. (new MutationObserver(
  2159. function(ms)
  2160. {
  2161. for (let m of ms)
  2162. janitor(m.addedNodes);
  2163. }
  2164. )).observe(
  2165. document.documentElement, {
  2166. childList: true,
  2167. subtree: true
  2168. }
  2169. );
  2170. }
  2171. /**/
  2172. }
  2173. };
  2174.  
  2175. scripts['megogo.net'] = {
  2176. now: function()
  2177. {
  2178. Object.defineProperty(win, "adBlock", {
  2179. get: () => false,
  2180. set: () => null,
  2181. enumerable : true
  2182. });
  2183. Object.defineProperty(win, "showAdBlockMessage", {
  2184. get: () => (() => null),
  2185. set: () => null,
  2186. enumerable: true
  2187. });
  2188. }
  2189. };
  2190.  
  2191. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2192.  
  2193. scripts['overclockers.ru'] = {
  2194. now: function()
  2195. {
  2196. createStyle('.fixoldhtml {display:block!important}');
  2197. if (!isChrome && !isOpera)
  2198. return; // Looks like my code works only in Chrome-like browsers
  2199. let noContentYet = true;
  2200. function jWrap()
  2201. {
  2202. win.$ = new Proxy(
  2203. win.$, {
  2204. apply: function(_$, _this, args)
  2205. {
  2206. let _ret = _$.apply(_this, args);
  2207. if (_ret[0] === document.body)
  2208. _ret.html = () => console.log('Anti-adblock prevented.');
  2209. return _ret;
  2210. }
  2211. }
  2212. );
  2213. win.jQuery = win.$;
  2214. }
  2215. (function jReady()
  2216. {
  2217. if (!win.$ && noContentYet)
  2218. setTimeout(jReady, 0);
  2219. else
  2220. jWrap();
  2221. })();
  2222. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  2223. }
  2224. };
  2225. scripts['forums.overclockers.ru'] = {
  2226. now: function()
  2227. {
  2228. createStyle('.needblock {position: fixed; left: -10000px}');
  2229. Object.defineProperty(win, 'adblck', {
  2230. get: () => 'no',
  2231. set: () => null,
  2232. enumerable: true
  2233. });
  2234. }
  2235. };
  2236.  
  2237. scripts['pb.wtf'] = {
  2238. other: ['piratbit.org', 'piratbit.ru'],
  2239. dom: function()
  2240. {
  2241. createStyle('.reques,#result,tbody.row1:not([id]) {display: none !important}');
  2242. // image in the slider in the header
  2243. gardener('a[href^="/ex"],a[href$="=="]', /img/i, {root:'.release-navbar', observe:true, parent:'div'});
  2244. // ads in blocks on the page
  2245. gardener('a[href^="/topic/234257"]', /Как\sразместить/i, {siblings:-1, root:'#main_content', observe:true, parent:'span[style]'});
  2246. // line above topic content
  2247. gardener('.re_top1', /./, {root:'#main_content', parent:'.hidden-sm'});
  2248. }
  2249. };
  2250.  
  2251. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  2252.  
  2253. scripts['qrz.ru'] = {
  2254. now: function()
  2255. {
  2256. Object.defineProperty(win, 'ab', {
  2257. get:()=>false,
  2258. set:()=>null
  2259. });
  2260. Object.defineProperty(win, 'tryMessage', {
  2261. get:()=>(()=>null),
  2262. set:()=>null
  2263. });
  2264. }
  2265. };
  2266.  
  2267. scripts['razlozhi.ru'] = {
  2268. now: function()
  2269. {
  2270. for (let func of ['createShadowRoot', 'attachShadow'])
  2271. if (func in Element.prototype)
  2272. Element.prototype[func] = function(){ return this.cloneNode(); };
  2273. }
  2274. };
  2275.  
  2276. scripts['rbc.ru'] = {
  2277. dom: function()
  2278. {
  2279. let _preventDefault = Event.prototype.preventDefault;
  2280. Event.prototype.preventDefault = function preventDefault()
  2281. {
  2282. let t = this.target;
  2283. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2284. throw new Error('an.yandex redirect prevention');
  2285. return _preventDefault.call(this);
  2286. };
  2287.  
  2288. function cleaner(nodes)
  2289. {
  2290. for (let node of nodes)
  2291. {
  2292. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2293. continue;
  2294. node.classList.remove('js-yandex-counter');
  2295. node.removeAttribute('data-yandex-name');
  2296. node.removeAttribute('data-yandex-params');
  2297. }
  2298. }
  2299. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2300.  
  2301. (new MutationObserver(
  2302. ms => { for (let m of ms) cleaner(m.addedNodes); }
  2303. )).observe(_de, {childList: true, subtree: true});
  2304. }
  2305. };
  2306.  
  2307. scripts['rp5.ru'] = {
  2308. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2309. dom: function()
  2310. {
  2311. createStyle('#bannerBottom {display: none!important}');
  2312. let co = document.querySelector('#content');
  2313. if (!co)
  2314. return;
  2315. let nodes = co.parentNode.childNodes,
  2316. i = nodes.length;
  2317. while (i--)
  2318. if (nodes[i] !== co)
  2319. nodes[i].parentNode.removeChild(nodes[i]);
  2320. }
  2321. };
  2322.  
  2323. scripts['rustorka.com'] = {
  2324. other: ['rumedia.ws'],
  2325. now: function()
  2326. {
  2327. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  2328. id: 'tempHidingStyles'
  2329. }, true);
  2330. preventPopups();
  2331. },
  2332. dom: function()
  2333. {
  2334. for (let o of document.querySelectorAll('IMG, A'))
  2335. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2336. (o.clientWidth === 300 && o.clientHeight === 250))
  2337. {
  2338. while (o && o.tagName !== 'A')
  2339. o = o.parentNode;
  2340. if (o)
  2341. _setAttribute.call(o, 'style', 'display: none !important');
  2342. }
  2343. let s = document.querySelector('#tempHidingStyles');
  2344. s.parentNode.removeChild(s);
  2345. }
  2346. };
  2347.  
  2348. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2349.  
  2350. scripts['sports.ru'] = function()
  2351. {
  2352. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2353. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2354. // extra functionality: shows/hides panel at the top depending on scroll direction
  2355. createStyle([
  2356. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2357. '.user-panel-up { top: -40px!important }'
  2358. ], {id: 'userPanelSlide'}, false);
  2359. (function lookForPanel()
  2360. {
  2361. let panel = document.querySelector('.user-panel__fixed');
  2362. if (!panel)
  2363. setTimeout(lookForPanel, 100);
  2364. else
  2365. window.addEventListener(
  2366. 'wheel', function(e)
  2367. {
  2368. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2369. panel.classList.add('user-panel-up');
  2370. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2371. panel.classList.remove('user-panel-up');
  2372. }, false
  2373. );
  2374. })();
  2375. };
  2376.  
  2377. scripts['vk.com'] = () => gardener('div[data-post-id]', /wall_marked_as_ads/, {root: '#page_wall_posts', observe: true});
  2378.  
  2379. scripts['yap.ru'] = {
  2380. other: ['yaplakal.com'],
  2381. dom: function()
  2382. {
  2383. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2384. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2385. }
  2386. };
  2387.  
  2388. scripts['rambler.ru'] = {
  2389. other: ['championat.com','gazeta.ru','lenta.ru'],
  2390. now: () => scriptLander(
  2391. function()
  2392. {
  2393. let getDomain = (name) => name.replace(/[^:]+:\/\/([^:/]+)[:/].*/, '$1').replace(/[^.]+\./,'');
  2394. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload');
  2395. let _set = _onload.set;
  2396. _onload.configurable = false;
  2397. _onload.set = function(func)
  2398. {
  2399. _set.call(
  2400. this, function(e)
  2401. {
  2402. let d = e.target.href ? getDomain(e.target.href) : null,
  2403. h = window.location.host;
  2404. if (d && e.target instanceof HTMLLinkElement &&
  2405. (d === 'rambler.ru' || d === h || h.indexOf('.'+d) > -1))
  2406. {
  2407. console.log('Blocked "onload" for', e.target.href);
  2408. return false;
  2409. }
  2410. return func.apply(this, arguments);
  2411. }
  2412. );
  2413. };
  2414. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  2415. // fake global Adf object
  2416. let nt = new nullTools();
  2417. nt.define(win, 'Adf', nt.proxy({
  2418. banner: nt.proxy({
  2419. sspScroll: nt.func(),
  2420. ssp: nt.func()
  2421. })
  2422. }));
  2423. // extra script for partner news on gazeta.ru
  2424. if (!location.host.includes('gazeta.ru'))
  2425. return;
  2426. (new MutationObserver(
  2427. function(ms)
  2428. {
  2429. let m, node, header;
  2430. for (m of ms) for (node of m.addedNodes)
  2431. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  2432. {
  2433. header = node.querySelector('.sausage-header');
  2434. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  2435. node.style.display = 'none';
  2436. }
  2437. }
  2438. )).observe(document.documentElement, { childList:true, subtree: true });
  2439. }, nullTools
  2440. )
  2441. };
  2442.  
  2443. scripts['reactor.cc'] = {
  2444. other: ['joyreactor.cc', 'pornreactor.cc'],
  2445. now: function()
  2446. {
  2447. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  2448. },
  2449. click: function(e)
  2450. {
  2451. let node = e.target;
  2452. if (node.nodeType === Node.ELEMENT_NODE &&
  2453. node.style.position === 'absolute' &&
  2454. node.style.zIndex > 0)
  2455. node.parentNode.removeChild(node);
  2456. },
  2457. dom: function()
  2458. {
  2459. let words = new RegExp(
  2460. 'блокировщика рекламы'
  2461. .split('')
  2462. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2463. .join('')
  2464. .replace(' ', '\\s*')
  2465. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2466. 'i'),
  2467. can;
  2468. function deeper(spider)
  2469. {
  2470. let c, l, n;
  2471. if (words.test(spider.innerText))
  2472. {
  2473. if (spider.nodeType === Node.TEXT_NODE)
  2474. return true;
  2475. c = spider.childNodes;
  2476. l = c.length;
  2477. n = 0;
  2478. while(l--)
  2479. if (deeper(c[l]), can)
  2480. n++;
  2481. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2482. can.push(spider);
  2483. return false;
  2484. }
  2485. return true;
  2486. }
  2487. function probe()
  2488. {
  2489. if (words.test(document.body.innerText))
  2490. {
  2491. can = [];
  2492. deeper(document.body);
  2493. let i = can.length, spider;
  2494. while(i--) {
  2495. spider = can[i];
  2496. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2497. _setAttribute.call(spider, 'style', 'background:none!important');
  2498. }
  2499. }
  2500. }
  2501. (new MutationObserver(probe))
  2502. .observe(document, { childList:true, subtree:true });
  2503. }
  2504. };
  2505.  
  2506. scripts['auto.ru'] = function()
  2507. {
  2508. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2509. let userAdsListAds = (
  2510. '.listing-list > .listing-item,'+
  2511. '.listing-item_type_fixed.listing-item'
  2512. );
  2513. let catalogAds = (
  2514. 'div[class*="layout_catalog-inline"],'+
  2515. 'div[class$="layout_horizontal"]'
  2516. );
  2517. let otherAds = (
  2518. '.advt_auto,'+
  2519. '.sidebar-block,'+
  2520. '.pager-listing + div[class],'+
  2521. '.card > div[class][style],'+
  2522. '.sidebar > div[class],'+
  2523. '.main-page__section + div[class],'+
  2524. '.listing > tbody'
  2525. );
  2526. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2527. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2528. gardener(otherAds, words);
  2529. };
  2530.  
  2531. scripts['rsload.net'] = {
  2532. load: function()
  2533. {
  2534. let dis = document.querySelector('label[class*="cb-disable"]');
  2535. if (dis)
  2536. dis.click();
  2537. },
  2538. click: function(e)
  2539. {
  2540. let t = e.target;
  2541. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2542. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2543. }
  2544. };
  2545.  
  2546. let domain, name;
  2547. // add alternate domain names if present
  2548. for (name in scripts) if (scripts[name].other)
  2549. for (domain of scripts[name].other) if (!(domain in scripts))
  2550. scripts[domain] = scripts[name];
  2551. // look for current domain in the list and run appropriate code
  2552. domain = document.domain;
  2553. while (domain.indexOf('.') > -1)
  2554. {
  2555. if (domain in scripts)
  2556. {
  2557. if (typeof scripts[domain] === 'function')
  2558. {
  2559. document.addEventListener ('DOMContentLoaded', scripts[domain], false);
  2560. break;
  2561. }
  2562. for (name in scripts[domain])
  2563. switch(name)
  2564. {
  2565. case 'other':
  2566. break;
  2567. case 'now':
  2568. scripts[domain][name]();
  2569. break;
  2570. case 'load':
  2571. window.addEventListener('load', scripts[domain][name], false);
  2572. break;
  2573. case 'dom':
  2574. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2575. break;
  2576. default:
  2577. document.addEventListener (name, scripts[domain][name], false);
  2578. }
  2579. }
  2580. domain = domain.slice(domain.indexOf('.') + 1);
  2581. }
  2582. })();