RU AdList JS Fixes

try to take over the world!

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

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