RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20170819.1
  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. }
  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. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1519. return;
  1520. }
  1521.  
  1522. scriptLander(
  1523. function()
  1524. {
  1525. function open()
  1526. {
  1527. '[native code]';
  1528. console.log('Site attempted to open a new window', arguments);
  1529. return {
  1530. document: {
  1531. write: () => {},
  1532. writeln: () => {}
  1533. }
  1534. };
  1535. }
  1536.  
  1537. function clickHandler(e)
  1538. {
  1539. let link = e.target;
  1540. if (!link.parentNode || !e.isTrusted ||
  1541. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  1542. {
  1543. e.preventDefault();
  1544. console.log('Blocked suspicious click event', e, 'on', e.target);
  1545. }
  1546. }
  1547.  
  1548. createWindowOpenWrapper(open, clickHandler);
  1549.  
  1550. console.log('Popup prevention enabled.');
  1551. }, createWindowOpenWrapper
  1552. );
  1553. }
  1554.  
  1555. // Helper function to close background tab if site opens itself in a new tab and then
  1556. // loads a 3rd-party page in the background one (thus performing background redirect).
  1557. function preventPopunders()
  1558. {
  1559. // create "close_me" event to call high-level window.close()
  1560. let eventName = 'close_me_' + Math.random().toString(36).substr(2);
  1561. let callClose = () => (console.log('close call'), window.close());
  1562. window.addEventListener(eventName, callClose, true);
  1563.  
  1564. scriptLander(
  1565. function()
  1566. {
  1567. let _open = window.open,
  1568. parseURL = document.createElement('A');
  1569. // get host of a provided URL with help of an anchor object
  1570. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1571. let getHost = (url) => (parseURL.href = url, parseURL.host);
  1572. // site went to a new tab and attempts to unload
  1573. // call for high-level close through event
  1574. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1575. // check is URL local or goes to different site
  1576. function isLocal(url)
  1577. {
  1578. let loc = window.location;
  1579. if (url === loc.pathname || url === loc.href)
  1580. return true; // URL points to current pathname or full address
  1581. let host = getHost(url),
  1582. site = loc.host;
  1583. if (host === '')
  1584. return false; // URLs with unusual protocol may have empty 'host'
  1585. if (host.length > site.length)
  1586. [site, host] = [host, site];
  1587. return site.includes(host, site.length - host.length);
  1588. }
  1589.  
  1590. function open(url)
  1591. {
  1592. '[native code]';
  1593. if (url && isLocal(url))
  1594. window.addEventListener('unload', closeWindow, true);
  1595. /*jshint validthis:true */
  1596. return _open.apply(this, arguments);
  1597. }
  1598.  
  1599. function clickHandler(e)
  1600. {
  1601. if (!e.target.parentNode || !e.isTrusted)
  1602. window.addEventListener('unload', closeWindow, true);
  1603. }
  1604.  
  1605. createWindowOpenWrapper(open, clickHandler);
  1606.  
  1607. console.log("Background redirect prevention enabled.");
  1608. }, [createWindowOpenWrapper, 'let eventName="'+eventName+'"']
  1609. );
  1610. }
  1611.  
  1612. // Mix between check for popups and popunders
  1613. // Significantly more agressive than both and can't be used as universal solution
  1614. function preventPopMix()
  1615. {
  1616. if (inIFrame)
  1617. {
  1618. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1619. return;
  1620. }
  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. window.addEventListener(
  1711. 'message', function(e)
  1712. {
  1713. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1714. return;
  1715. let src = e.data.href;
  1716. for (let frame of document.querySelectorAll('iframe'))
  1717. if (frame.contentWindow === e.source)
  1718. {
  1719. if (frame.hasAttribute('sandbox'))
  1720. {
  1721. if (!frame.sandbox.has('allow-popups'))
  1722. return; // exit frame since it's already sandboxed and popups are blocked
  1723. // remove allow-popups if frame already sandboxed
  1724. frame.sandbox.remove('allow-popups');
  1725. } else {
  1726. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1727. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1728. // but to apply content must be reloaded and this script will re-apply it in the result
  1729. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1730. }
  1731. console.log('Disallowed popups from iframe', frame);
  1732.  
  1733. // reload frame content to apply restrictions
  1734. if (!src) {
  1735. src = frame.src;
  1736. console.log('Unable to get current iframe location, reloading from src', src);
  1737. } else
  1738. console.log('Reloading iframe with URL', src);
  1739. frame.src = 'about:blank';
  1740. frame.src = src;
  1741. }
  1742. }, false
  1743. );
  1744. }
  1745.  
  1746. // === Scripts for specific domains ===
  1747.  
  1748. let scripts = {};
  1749. // prevent popups and redirects block
  1750. // Popups
  1751. scripts.preventPopups = {
  1752. other: [
  1753. 'biqle.ru',
  1754. 'chaturbate.com',
  1755. 'dfiles.ru',
  1756. 'hentaiz.org',
  1757. 'mirrorcreator.com',
  1758. 'online-multy.ru',
  1759. 'radikal.ru',
  1760. 'seedoff.cc', 'seedoff.tv',
  1761. 'tapochek.net', 'thepiratebay.org', 'torseed.net',
  1762. 'unionpeer.com',
  1763. 'zippyshare.com'
  1764. ],
  1765. now: preventPopups
  1766. };
  1767. // Popunders (background redirect)
  1768. scripts.preventPopunders = {
  1769. other: [
  1770. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1771. 'perfectgirls.net'
  1772. ],
  1773. now: preventPopunders
  1774. };
  1775. // PopMix (both types of popups encountered on site)
  1776. scripts.preventPopMix = {
  1777. other: [
  1778. 'openload.co',
  1779. 'turbobit.net'
  1780. ],
  1781. now: preventPopMix
  1782. };
  1783.  
  1784. // other
  1785. scripts['4pda.ru'] = {
  1786. now: function()
  1787. {
  1788. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  1789. let hStyle,
  1790. isForum = document.location.href.search('/forum/') !== -1,
  1791. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  1792. afterClean = () => remove(hStyle);
  1793.  
  1794. function beforeClean()
  1795. {
  1796. // attach styles before document displayed
  1797. hStyle = createStyle([
  1798. 'html { overflow-y: scroll }',
  1799. 'section[id] {'+(
  1800. 'position: absolute;'+
  1801. 'width: 100%'
  1802. )+'}',
  1803. 'article + aside * { display: none !important }',
  1804. '#header + div:after {'+(
  1805. 'content: "";'+
  1806. 'position: fixed;'+
  1807. 'top: 0;'+
  1808. 'left: 0;'+
  1809. 'width: 100%;'+
  1810. 'height: 100%;'+
  1811. 'background-color: #E6E7E9'
  1812. )+'}',
  1813. // http://codepen.io/Beaugust/pen/DByiE
  1814. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  1815. 'article + aside:after {'+(
  1816. 'content: "";'+
  1817. 'position: absolute;'+
  1818. 'width: 150px;'+
  1819. 'height: 150px;'+
  1820. 'top: 150px;'+
  1821. 'left: 50%;'+
  1822. 'margin-top: -75px;'+
  1823. 'margin-left: -75px;'+
  1824. 'box-sizing: border-box;'+
  1825. 'border-radius: 100%;'+
  1826. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  1827. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  1828. 'animation: spin 2s infinite linear'
  1829. )+'}'
  1830. ], {id:'ubrHider'}, true);
  1831.  
  1832. // display content of a page if time to load a page is more than 2 seconds to avoid
  1833. // blocking access to a page if it is loading for too long or stuck in a loading state
  1834. setTimeout(2000, afterClean);
  1835. }
  1836.  
  1837. createStyle([
  1838. '#nav .use-ad { display: block !important }',
  1839. 'article:not(.post) + article:not(#id),'+
  1840. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  1841. ]);
  1842.  
  1843. if (!isForum)
  1844. beforeClean();
  1845.  
  1846. // save links to non-overridden functions to use later
  1847. let protectedElems;
  1848. // protect/hide changed attributes in case site attempt to restore them
  1849. function styleProtector(eventMode)
  1850. {
  1851. let _toLowerCase = String.prototype.toLowerCase,
  1852. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  1853. protectedElems = new WeakMap();
  1854. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  1855. {
  1856. let originalFunction = element.prototype[functionName];
  1857. element.prototype[functionName] = function wrapper()
  1858. {
  1859. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  1860. return returnIfProtected(this, arguments);
  1861. return originalFunction.apply(this, arguments);
  1862. };
  1863. }
  1864. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  1865. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  1866. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  1867. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  1868. if (!eventMode)
  1869. return protectedElems;
  1870. else
  1871. {
  1872. let e = document.createEvent('Event');
  1873. e.initEvent('protoOverride', false, false);
  1874. window.protectedElems = protectedElems;
  1875. window.dispatchEvent(e);
  1876. }
  1877. }
  1878. if (!isFirefox)
  1879. protectedElems = styleProtector(false);
  1880. else
  1881. {
  1882. let script = document.createElement('script');
  1883. script.textContent = '(' + styleProtector.toString() + ')(true);';
  1884. window.addEventListener(
  1885. 'protoOverride', function protoOverrideCallback(e)
  1886. {
  1887. if (win.protectedElems) {
  1888. protectedElems = win.protectedElems;
  1889. delete win.protectedElems;
  1890. }
  1891. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  1892. }, true
  1893. );
  1894. _appendChild(script);
  1895. _removeChild(script);
  1896. }
  1897.  
  1898. // clean a page
  1899. window.addEventListener(
  1900. 'DOMContentLoaded', function()
  1901. {
  1902. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  1903. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  1904.  
  1905. if (isForum)
  1906. {
  1907. let si = document.querySelector('#logostrip');
  1908. if (si)
  1909. remove(si.parentNode.nextSibling);
  1910. }
  1911.  
  1912. if (document.location.href.search('/forum/dl/') !== -1) {
  1913. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+
  1914. ';background-color:black!important');
  1915. for (let itm of document.querySelectorAll('body>div'))
  1916. if (!itm.querySelector('.dw-fdwlink'))
  1917. remove(itm);
  1918. }
  1919.  
  1920. if (isForum) // Do not continue if it's a forum
  1921. return;
  1922.  
  1923. {
  1924. let si = document.querySelector('#header');
  1925. if (si)
  1926. {
  1927. let rem = si.previousSibling;
  1928. while (rem)
  1929. {
  1930. si = rem.previousSibling;
  1931. remove(rem);
  1932. rem = si;
  1933. }
  1934. }
  1935. }
  1936.  
  1937. for (let itm of document.querySelectorAll('#nav li[class]'))
  1938. if (itm && itm.querySelector('a[href^="/tag/"]'))
  1939. remove(itm);
  1940.  
  1941. let style, result,
  1942. fakeStyles = new WeakMap(),
  1943. styleProxy = {
  1944. get: function(target, prop)
  1945. {
  1946. let fakeStyle = fakeStyles.get(target);
  1947. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  1948. },
  1949. set: function(target, prop, value)
  1950. {
  1951. let fakeStyle = fakeStyles.get(target);
  1952. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  1953. return value;
  1954. }
  1955. };
  1956. for (let itm of document.querySelectorAll('DIV, A'))
  1957. {
  1958. if (itm.tagName ==='DIV' &&
  1959. itm.offsetWidth > 0.95 * width() &&
  1960. itm.offsetHeight > 0.85 * height())
  1961. {
  1962. style = window.getComputedStyle(itm, null);
  1963. result = [];
  1964.  
  1965. if (style.backgroundImage !== 'none')
  1966. result.push('background-image:none!important');
  1967.  
  1968. if (style.backgroundColor !== 'transparent' &&
  1969. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  1970. result.push('background-color:transparent!important');
  1971.  
  1972. if (result.length)
  1973. {
  1974. if (itm.getAttribute('style'))
  1975. result.unshift(itm.getAttribute('style'));
  1976.  
  1977. fakeStyles.set(itm.style, {
  1978. 'backgroundImage': itm.style.backgroundImage,
  1979. 'backgroundColor': itm.style.backgroundColor
  1980. });
  1981.  
  1982. try {
  1983. Object.defineProperty(itm, 'style', {
  1984. value: new Proxy(itm.style, styleProxy),
  1985. enumerable: true
  1986. });
  1987. } catch (e) {
  1988. console.log('Unable to protect style property.', e);
  1989. }
  1990.  
  1991. if (protectedElems)
  1992. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  1993.  
  1994. _setAttribute.call(itm, 'style', result.join(';'));
  1995. }
  1996. }
  1997. if (itm.tagName ==='A' &&
  1998. (itm.offsetWidth > 0.95 * width() ||
  1999. itm.offsetHeight > 0.85 * height()))
  2000. {
  2001. if (protectedElems)
  2002. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2003.  
  2004. _setAttribute.call(itm, 'style', 'display:none!important');
  2005. }
  2006. }
  2007.  
  2008. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2009. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2010. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2011. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2012. remove(itm);
  2013.  
  2014. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2015.  
  2016. // display content of the page
  2017. afterClean();
  2018. }
  2019. );
  2020. }
  2021. };
  2022.  
  2023. scripts['allmovie.pro'] = {
  2024. other: ['rufilmtv.org'],
  2025. dom: function()
  2026. {
  2027. // pretend to be Android to make site use different played for ads
  2028. if (isSafari)
  2029. return;
  2030. Object.defineProperty(navigator, 'userAgent', {
  2031. 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'; },
  2032. enumerable: true
  2033. });
  2034. }
  2035. };
  2036.  
  2037. scripts['anidub-online.ru'] = {
  2038. other: ['online.anidub.com'],
  2039. dom: function()
  2040. {
  2041. if (win.ogonekstart1)
  2042. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2043. },
  2044. now: () => createStyle([
  2045. '.background {background: none!important;}',
  2046. '.background > script + div,'+
  2047. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2048. '{display:none!important}'
  2049. ])
  2050. };
  2051.  
  2052. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2053.  
  2054. scripts['fishki.net'] = () => gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров/);
  2055.  
  2056. scripts['gidonline.club'] = {
  2057. now: () => createStyle('.tray > div[style] {display: none!important}')
  2058. };
  2059.  
  2060. scripts['hdgo.cc'] = {
  2061. other: ['46.30.43.38', 'couber.be'],
  2062. now: () => (new MutationObserver(
  2063. function(ms)
  2064. {
  2065. let m, node;
  2066. for (m of ms) for (node of m.addedNodes)
  2067. if (node.tagName === 'SCRIPT' && _getAttribute.call(node, 'onerror') !== null)
  2068. node.removeAttribute('onerror');
  2069. }
  2070. )).observe(document.documentElement, { childList:true, subtree: true })
  2071. };
  2072.  
  2073. scripts['gismeteo.ru'] = {
  2074. other: ['gismeteo.ua'],
  2075. dom: () => gardener('div > a[target^="_"]', /Яндекс\.Директ/i, { root: 'body', observe: true, parent: 'div[class*="frame"]'})
  2076. };
  2077.  
  2078. scripts['hdrezka.me'] = {
  2079. now: function()
  2080. {
  2081. Object.defineProperty(win, 'fuckAdBlock', {
  2082. value: { onDetected: () => console.log('Pretending to be an ABP detector.') },
  2083. enumerable: true
  2084. });
  2085. Object.defineProperty(win, 'ab', {
  2086. value: false,
  2087. enumerable: true
  2088. });
  2089. },
  2090. dom: () => gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i)
  2091. };
  2092.  
  2093. scripts['imageban.ru'] = {
  2094. now: preventPopunders,
  2095. dom: () => win.addEventListener(
  2096. 'unload', function()
  2097. {
  2098. window.location.hash = 'x'+Math.random().toString(36).substr(2);
  2099. }, true
  2100. )
  2101. };
  2102.  
  2103. scripts['mail.ru'] = {
  2104. now: function()
  2105. {
  2106. // Trick to prevent mail.ru from removing 3rd-party styles
  2107. scriptLander(
  2108. () => Object.defineProperty(Object.prototype, 'restoreVisibility', {
  2109. get: () => (() => null),
  2110. set: () => null
  2111. })
  2112. );
  2113. /* Experimental code, disabled for end users for now
  2114. // Ads removal on e.mail.ru
  2115. if (window.location.host === 'e.mail.ru')
  2116. {
  2117. let selector = (
  2118. '.b-datalist div[class]:not([id]) > div[class]:not([class*="js-"]),'+
  2119. '.b-letter div[class]:not([id]) > div[class]:not([class*="js-"]):not([class*="drop"]):not([class*="letter"]):not([style]):not([id]),'+
  2120. 'div[id]:not([class]) > div[id][class]:not([class*="js-"]):not([class*="drop"]):not([style])'
  2121. );
  2122. let janitor = function(nodes)
  2123. {
  2124. let color;
  2125. for (let node of nodes)
  2126. {
  2127. if (node.nodeType !== Node.ELEMENT_NODE)
  2128. continue;
  2129. color = window.getComputedStyle(node).backgroundColor;
  2130. if (/^rgb\(/.test(color) && color !== 'rgb(255, 255, 255)')
  2131. {
  2132. node.style.display = 'none';
  2133. console.log('Hide node:', node);
  2134. }
  2135. }
  2136. };
  2137. janitor(document.querySelectorAll(selector));
  2138. (new MutationObserver(
  2139. function(ms)
  2140. {
  2141. for (let m of ms)
  2142. janitor(m.addedNodes);
  2143. }
  2144. )).observe(
  2145. document.documentElement, {
  2146. childList: true,
  2147. subtree: true
  2148. }
  2149. );
  2150. }
  2151. /**/
  2152. }
  2153. };
  2154.  
  2155. scripts['megogo.net'] = {
  2156. now: function()
  2157. {
  2158. Object.defineProperty(win, "adBlock", {
  2159. get: () => false,
  2160. set: () => null,
  2161. enumerable : true
  2162. });
  2163. Object.defineProperty(win, "showAdBlockMessage", {
  2164. get: () => (() => null),
  2165. set: () => null,
  2166. enumerable: true
  2167. });
  2168. }
  2169. };
  2170.  
  2171. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2172.  
  2173. scripts['overclockers.ru'] = {
  2174. now: function()
  2175. {
  2176. createStyle('.fixoldhtml {display:block!important}');
  2177. if (!isChrome && !isOpera)
  2178. return; // Looks like my code works only in Chrome-like browsers
  2179. let noContentYet = true;
  2180. function jWrap()
  2181. {
  2182. win.$ = new Proxy(
  2183. win.$, {
  2184. apply: function(_$, _this, args)
  2185. {
  2186. let _ret = _$.apply(_this, args);
  2187. if (_ret[0] === document.body)
  2188. _ret.html = () => console.log('Anti-adblock prevented.');
  2189. return _ret;
  2190. }
  2191. }
  2192. );
  2193. win.jQuery = win.$;
  2194. }
  2195. (function jReady()
  2196. {
  2197. if (!win.$ && noContentYet)
  2198. setTimeout(jReady, 0);
  2199. else
  2200. jWrap();
  2201. })();
  2202. document.addEventListener ('DOMContentLoaded', () => (noContentYet = false), false);
  2203. }
  2204. };
  2205. scripts['forums.overclockers.ru'] = {
  2206. now: function()
  2207. {
  2208. createStyle('.needblock {position: fixed; left: -10000px}');
  2209. Object.defineProperty(win, 'adblck', {
  2210. get: () => 'no',
  2211. set: () => null,
  2212. enumerable: true
  2213. });
  2214. }
  2215. };
  2216.  
  2217. scripts['pb.wtf'] = {
  2218. other: ['piratbit.org', 'piratbit.ru'],
  2219. dom: function()
  2220. {
  2221. createStyle('.reques,#result,tbody.row1:not([id]) {display: none !important}');
  2222. // image in the slider in the header
  2223. gardener('a[href^="/ex"],a[href$="=="]', /img/i, {root:'.release-navbar', observe:true, parent:'div'});
  2224. // ads in blocks on the page
  2225. gardener('a[href^="/topic/234257"]', /Как\sразместить/i, {siblings:-1, root:'#main_content', observe:true, parent:'span[style]'});
  2226. // line above topic content
  2227. gardener('.re_top1', /./, {root:'#main_content', parent:'.hidden-sm'});
  2228. }
  2229. };
  2230.  
  2231. scripts['pikabu.ru'] = () => gardener('.story', /story__sponsor|story__gag|profile\/ads"/i, {root: '.inner_wrap', observe: true});
  2232.  
  2233. scripts['qrz.ru'] = {
  2234. now: function()
  2235. {
  2236. Object.defineProperty(win, 'ab', {
  2237. get:()=>false,
  2238. set:()=>null
  2239. });
  2240. Object.defineProperty(win, 'tryMessage', {
  2241. get:()=>(()=>null),
  2242. set:()=>null
  2243. });
  2244. }
  2245. };
  2246.  
  2247. scripts['razlozhi.ru'] = {
  2248. now: function()
  2249. {
  2250. for (let func of ['createShadowRoot', 'attachShadow'])
  2251. if (func in Element.prototype)
  2252. Element.prototype[func] = function(){ return this.cloneNode(); };
  2253. }
  2254. };
  2255.  
  2256. scripts['rbc.ru'] = {
  2257. dom: function()
  2258. {
  2259. let _preventDefault = Event.prototype.preventDefault;
  2260. Event.prototype.preventDefault = function preventDefault()
  2261. {
  2262. let t = this.target;
  2263. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2264. throw new Error('an.yandex redirect prevention');
  2265. return _preventDefault.call(this);
  2266. };
  2267.  
  2268. function cleaner(nodes)
  2269. {
  2270. for (let node of nodes)
  2271. {
  2272. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2273. continue;
  2274. node.classList.remove('js-yandex-counter');
  2275. node.removeAttribute('data-yandex-name');
  2276. node.removeAttribute('data-yandex-params');
  2277. }
  2278. }
  2279. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2280.  
  2281. (new MutationObserver(
  2282. ms => { for (let m of ms) cleaner(m.addedNodes); }
  2283. )).observe(_de, {childList: true, subtree: true});
  2284. }
  2285. };
  2286.  
  2287. scripts['rp5.ru'] = {
  2288. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2289. dom: function()
  2290. {
  2291. createStyle('#bannerBottom {display: none!important}');
  2292. let co = document.querySelector('#content');
  2293. if (!co)
  2294. return;
  2295. let nodes = co.parentNode.childNodes,
  2296. i = nodes.length;
  2297. while (i--)
  2298. if (nodes[i] !== co)
  2299. nodes[i].parentNode.removeChild(nodes[i]);
  2300. }
  2301. };
  2302.  
  2303. scripts['rustorka.com'] = {
  2304. other: ['rumedia.ws'],
  2305. now: function()
  2306. {
  2307. createStyle('.header > div:not(.head-block) a, #sidebar1 img, #logo img {opacity:0!important}', {
  2308. id: 'tempHidingStyles'
  2309. }, true);
  2310. preventPopups();
  2311. },
  2312. dom: function()
  2313. {
  2314. for (let o of document.querySelectorAll('IMG, A'))
  2315. if ((o.clientWidth === 728 && o.clientHeight === 90) ||
  2316. (o.clientWidth === 300 && o.clientHeight === 250))
  2317. {
  2318. while (o && o.tagName !== 'A')
  2319. o = o.parentNode;
  2320. if (o)
  2321. _setAttribute.call(o, 'style', 'display: none !important');
  2322. }
  2323. let s = document.querySelector('#tempHidingStyles');
  2324. s.parentNode.removeChild(s);
  2325. }
  2326. };
  2327.  
  2328. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2329.  
  2330. scripts['sports.ru'] = function()
  2331. {
  2332. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2333. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2334. // extra functionality: shows/hides panel at the top depending on scroll direction
  2335. createStyle([
  2336. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2337. '.user-panel-up { top: -40px!important }'
  2338. ], {id: 'userPanelSlide'}, false);
  2339. (function lookForPanel()
  2340. {
  2341. let panel = document.querySelector('.user-panel__fixed');
  2342. if (!panel)
  2343. setTimeout(lookForPanel, 100);
  2344. else
  2345. window.addEventListener(
  2346. 'wheel', function(e)
  2347. {
  2348. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2349. panel.classList.add('user-panel-up');
  2350. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2351. panel.classList.remove('user-panel-up');
  2352. }, false
  2353. );
  2354. })();
  2355. };
  2356.  
  2357. scripts['vk.com'] = () => gardener('div[data-post-id]', /wall_marked_as_ads/, {root: '#page_wall_posts', observe: true});
  2358.  
  2359. scripts['yap.ru'] = {
  2360. other: ['yaplakal.com'],
  2361. dom: function()
  2362. {
  2363. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2364. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2365. }
  2366. };
  2367.  
  2368. scripts['rambler.ru'] = {
  2369. other: ['championat.com','gazeta.ru','lenta.ru'],
  2370. now: () => scriptLander(
  2371. function()
  2372. {
  2373. let getDomain = (name) => name.replace(/[^:]+:\/\/([^:/]+)[:/].*/, '$1').replace(/[^.]+\./,'');
  2374. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload');
  2375. let _set = _onload.set;
  2376. _onload.configurable = false;
  2377. _onload.set = function(func)
  2378. {
  2379. _set.call(
  2380. this, function(e)
  2381. {
  2382. let d = e.target.href ? getDomain(e.target.href) : null,
  2383. h = window.location.host;
  2384. if (d && e.target instanceof HTMLLinkElement &&
  2385. (d === 'rambler.ru' || d === h || h.indexOf('.'+d) > -1))
  2386. {
  2387. console.log('Blocked "onload" for', e.target.href);
  2388. return false;
  2389. }
  2390. return func.apply(this, arguments);
  2391. }
  2392. );
  2393. };
  2394. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  2395. // fake global Adf object
  2396. let nt = new nullTools();
  2397. nt.define(win, 'Adf', nt.proxy({
  2398. banner: nt.proxy({
  2399. sspScroll: nt.func(),
  2400. ssp: nt.func()
  2401. })
  2402. }));
  2403. // extra script for partner news on gazeta.ru
  2404. if (!location.host.includes('gazeta.ru'))
  2405. return;
  2406. (new MutationObserver(
  2407. function(ms)
  2408. {
  2409. let m, node, header;
  2410. for (m of ms) for (node of m.addedNodes)
  2411. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  2412. {
  2413. header = node.querySelector('.sausage-header');
  2414. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  2415. node.style.display = 'none';
  2416. }
  2417. }
  2418. )).observe(document.documentElement, { childList:true, subtree: true });
  2419. }, nullTools
  2420. )
  2421. };
  2422.  
  2423. scripts['reactor.cc'] = {
  2424. other: ['joyreactor.cc', 'pornreactor.cc'],
  2425. now: function()
  2426. {
  2427. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  2428. },
  2429. click: function(e)
  2430. {
  2431. let node = e.target;
  2432. if (node.nodeType === Node.ELEMENT_NODE &&
  2433. node.style.position === 'absolute' &&
  2434. node.style.zIndex > 0)
  2435. node.parentNode.removeChild(node);
  2436. },
  2437. dom: function()
  2438. {
  2439. let words = new RegExp(
  2440. 'блокировщика рекламы'
  2441. .split('')
  2442. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  2443. .join('')
  2444. .replace(' ', '\\s*')
  2445. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  2446. 'i'),
  2447. can;
  2448. function deeper(spider)
  2449. {
  2450. let c, l, n;
  2451. if (words.test(spider.innerText))
  2452. {
  2453. if (spider.nodeType === Node.TEXT_NODE)
  2454. return true;
  2455. c = spider.childNodes;
  2456. l = c.length;
  2457. n = 0;
  2458. while(l--)
  2459. if (deeper(c[l]), can)
  2460. n++;
  2461. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  2462. can.push(spider);
  2463. return false;
  2464. }
  2465. return true;
  2466. }
  2467. function probe()
  2468. {
  2469. if (words.test(document.body.innerText))
  2470. {
  2471. can = [];
  2472. deeper(document.body);
  2473. let i = can.length, spider;
  2474. while(i--) {
  2475. spider = can[i];
  2476. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  2477. _setAttribute.call(spider, 'style', 'background:none!important');
  2478. }
  2479. }
  2480. }
  2481. (new MutationObserver(probe))
  2482. .observe(document, { childList:true, subtree:true });
  2483. }
  2484. };
  2485.  
  2486. scripts['auto.ru'] = function()
  2487. {
  2488. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2489. let userAdsListAds = (
  2490. '.listing-list > .listing-item,'+
  2491. '.listing-item_type_fixed.listing-item'
  2492. );
  2493. let catalogAds = (
  2494. 'div[class*="layout_catalog-inline"],'+
  2495. 'div[class$="layout_horizontal"]'
  2496. );
  2497. let otherAds = (
  2498. '.advt_auto,'+
  2499. '.sidebar-block,'+
  2500. '.pager-listing + div[class],'+
  2501. '.card > div[class][style],'+
  2502. '.sidebar > div[class],'+
  2503. '.main-page__section + div[class],'+
  2504. '.listing > tbody'
  2505. );
  2506. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  2507. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  2508. gardener(otherAds, words);
  2509. };
  2510.  
  2511. scripts['rsload.net'] = {
  2512. load: function()
  2513. {
  2514. let dis = document.querySelector('label[class*="cb-disable"]');
  2515. if (dis)
  2516. dis.click();
  2517. },
  2518. click: function(e)
  2519. {
  2520. let t = e.target;
  2521. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  2522. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  2523. }
  2524. };
  2525.  
  2526. let domain, name;
  2527. // add alternate domain names if present
  2528. for (name in scripts) if (scripts[name].other)
  2529. for (domain of scripts[name].other) if (!(domain in scripts))
  2530. scripts[domain] = scripts[name];
  2531. // look for current domain in the list and run appropriate code
  2532. domain = document.domain;
  2533. while (domain.indexOf('.') > -1)
  2534. {
  2535. if (domain in scripts)
  2536. {
  2537. if (typeof scripts[domain] === 'function')
  2538. {
  2539. document.addEventListener ('DOMContentLoaded', scripts[domain], false);
  2540. break;
  2541. }
  2542. for (name in scripts[domain])
  2543. switch(name)
  2544. {
  2545. case 'other':
  2546. break;
  2547. case 'now':
  2548. scripts[domain][name]();
  2549. break;
  2550. case 'load':
  2551. window.addEventListener('load', scripts[domain][name], false);
  2552. break;
  2553. case 'dom':
  2554. document.addEventListener('DOMContentLoaded', scripts[domain][name], false);
  2555. break;
  2556. default:
  2557. document.addEventListener (name, scripts[domain][name], false);
  2558. }
  2559. }
  2560. domain = domain.slice(domain.indexOf('.') + 1);
  2561. }
  2562. })();