RU AdList JS Fixes

try to take over the world!

目前為 2018-06-26 提交的版本,檢視 最新版本

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