RU AdList JS Fixes

try to take over the world!

当前为 2017-09-01 提交的版本,查看 最新版本

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