RU AdList JS Fixes

try to take over the world!

当前为 2017-11-07 提交的版本,查看 最新版本

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