RU AdList JS Fixes

try to take over the world!

目前為 2017-08-15 提交的版本,檢視 最新版本

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