RU AdList JS Fixes

try to take over the world!

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

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