RU AdList JS Fixes

try to take over the world!

目前为 2017-11-20 提交的版本,查看 最新版本

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