RU AdList JS Fixes

try to take over the world!

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

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