RU AdList JS Fixes

try to take over the world!

目前為 2018-01-14 提交的版本,檢視 最新版本

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