RU AdList JS Fixes

try to take over the world!

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

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