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