RU AdList JS Fixes

try to take over the world!

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

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