RU AdList JS Fixes

try to take over the world!

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

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