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.1
  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.  
  1451. wrapAPI(win);
  1452.  
  1453. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  1454. let _get_contentWindow = _contentWindow.get;
  1455. _contentWindow.get = function() {
  1456. let _cw = _get_contentWindow.apply(this, arguments);
  1457. if (_cw)
  1458. wrapAPI(_cw);
  1459. return _cw;
  1460. };
  1461. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  1462.  
  1463. win.stop = () => {
  1464. console.warn('window.stop() ...y tho?');
  1465. for (let sheet of document.styleSheets)
  1466. if (sheet.disabled) {
  1467. sheet.disabled = false;
  1468. console.log('Re-enabled:', sheet);
  1469. }
  1470. }
  1471. }
  1472. );
  1473.  
  1474. // === Helper functions ===
  1475.  
  1476. // function to search and remove nodes by content
  1477. // selector - standard CSS selector to define set of nodes to check
  1478. // words - regular expression to check content of the suspicious nodes
  1479. // params - object with multiple extra parameters:
  1480. // .log - display log in the console
  1481. // .hide - set display to none instead of removing from the page
  1482. // .parent - parent node to remove if content is found in the child node
  1483. // .siblings - number of simling nodes to remove (excluding text nodes)
  1484. let scRemove = (node) => node.parentNode.removeChild(node);
  1485. let scHide = function(node) {
  1486. let style = _getAttribute.call(node, 'style') || '',
  1487. hide = ';display:none!important;';
  1488. if (style.indexOf(hide) < 0)
  1489. _setAttribute.call(node, 'style', style + hide);
  1490. };
  1491.  
  1492. function scissors (selector, words, scope, params) {
  1493. let logger = (...args) => { if (params.log) console.log(...args) };
  1494. if (!scope.contains(document.body))
  1495. logger('[s] scope', scope);
  1496. let remFunc = (params.hide ? scHide : scRemove),
  1497. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1498. toRemove = [],
  1499. siblings;
  1500. for (let node of scope.querySelectorAll(selector)) {
  1501. // drill up to a parent node if specified, break if not found
  1502. if (params.parent) {
  1503. let old = node;
  1504. node = node.closest(params.parent);
  1505. if (node === null || node.contains(scope)) {
  1506. logger('[s] went out of scope with', old);
  1507. continue;
  1508. }
  1509. }
  1510. logger('[s] processing', node);
  1511. if (toRemove.includes(node))
  1512. continue;
  1513. if (words.test(node.innerHTML)) {
  1514. // skip node if already marked for removal
  1515. logger('[s] marked for removal');
  1516. toRemove.push(node);
  1517. // add multiple nodes if defined more than one sibling
  1518. siblings = Math.abs(params.siblings) || 0;
  1519. while (siblings) {
  1520. node = node[iterFunc];
  1521. if (!node) break; // can't go any further - exit
  1522. logger('[s] adding sibling node', node);
  1523. toRemove.push(node);
  1524. siblings -= 1;
  1525. }
  1526. }
  1527. }
  1528. let toSkip = [];
  1529. for (let node of toRemove)
  1530. if (!toRemove.every(other => other === node || !node.contains(other)))
  1531. toSkip.push(node);
  1532. if (toRemove.length)
  1533. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1534. for (let node of toRemove) if (!toSkip.includes(node))
  1535. remFunc(node);
  1536. }
  1537.  
  1538. // function to perform multiple checks if ads inserted with a delay
  1539. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1540. // also does 1 extra check when a page completely loads
  1541. // selector and words - passed dow to scissors
  1542. // params - object with multiple extra parameters:
  1543. // .log - display log in the console
  1544. // .root - selector to narrow down scope to scan;
  1545. // .observe - if true then check will be performed continuously;
  1546. // Other parameters passed down to scissors.
  1547. function gardener(selector, words, params) {
  1548. let logger = (...args) => { if(params.log) console.log(...args) };
  1549. params = params || {};
  1550. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1551. let scope;
  1552. let globalScope = [_de];
  1553. let domLoaded = false;
  1554. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1555. let onevent = e => {
  1556. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1557. for (let node of scope)
  1558. scissors(selector, words, node, params);
  1559. };
  1560. let repeater = n => {
  1561. if (!domLoaded && n) {
  1562. setTimeout(repeater, 500, n - 1);
  1563. scope = getScope(params.root);
  1564. if (!scope) // exit if the root element is not present on the page
  1565. return 0;
  1566. onevent({type: 'Repeater'});
  1567. }
  1568. };
  1569. repeater(20);
  1570. document.addEventListener(
  1571. 'DOMContentLoaded', (e) => {
  1572. domLoaded = true;
  1573. // narrow down scope to a specific element
  1574. scope = getScope(params.root);
  1575. if (!scope) // exit if the root element is not present on the page
  1576. return 0;
  1577. logger('[g] scope', scope);
  1578. // add observe mode if required
  1579. if (params.observe) {
  1580. let params = { childList:true, subtree: true };
  1581. let observer = new MutationObserver(
  1582. function(ms) {
  1583. for (let m of ms)
  1584. if (m.addedNodes.length)
  1585. onevent(m);
  1586. }
  1587. );
  1588. for (let node of scope)
  1589. observer.observe(node, params);
  1590. logger('[g] observer enabled');
  1591. }
  1592. onevent(e);
  1593. }, false);
  1594. // wait for a full page load to do one extra cut
  1595. win.addEventListener('load', onevent, false);
  1596. }
  1597.  
  1598. // wrap popular methods to open a new tab to catch specific behaviours
  1599. function createWindowOpenWrapper(openFunc) {
  1600. let _createElement = _Document.prototype.createElement,
  1601. _appendChild = _Element.prototype.appendChild,
  1602. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1603.  
  1604. let nt = new nullTools();
  1605. fakeNative(openFunc);
  1606.  
  1607. let parser = _createElement.call(document, 'a');
  1608. let openWhitelist = (url, parent) => {
  1609. parser.href = url;
  1610. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1611. parent.hostname === 'radikal.ru' && url === void 0;
  1612. };
  1613.  
  1614. let redefineOpen = (root) => {
  1615. if ('open' in root) {
  1616. let _open = root.open.bind(root);
  1617. nt.define(root, 'open', (...args) => {
  1618. if (openWhitelist(args[0], location)) {
  1619. console.log('Whitelisted popup:', ...args);
  1620. return _open(...args);
  1621. }
  1622. return openFunc(...args);
  1623. });
  1624. }
  1625. };
  1626. redefineOpen(win);
  1627.  
  1628. function createElement() {
  1629. '[native code]';
  1630. let el = _createElement.apply(this, arguments);
  1631. // redefine window.open in first-party frames
  1632. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1633. el.addEventListener('load', (e) => {
  1634. try {
  1635. redefineOpen(e.target.contentWindow);
  1636. } catch(ignore) {}
  1637. }, false);
  1638. return el;
  1639. }
  1640. fakeNative(createElement);
  1641.  
  1642. let redefineCreateElement = (obj) => {
  1643. for (let root of [obj.document, _Document.prototype]) if ('createElement' in root)
  1644. nt.define(root, 'createElement', createElement);
  1645. };
  1646. redefineCreateElement(win);
  1647.  
  1648. // wrap window.open in newly added first-party frames
  1649. _Element.prototype.appendChild = function appendChild() {
  1650. '[native code]';
  1651. let el = _appendChild.apply(this, arguments);
  1652. if (el instanceof HTMLIFrameElement)
  1653. try {
  1654. redefineOpen(el.contentWindow);
  1655. redefineCreateElement(el.contentWindow);
  1656. } catch(ignore) {}
  1657. return el;
  1658. };
  1659. fakeNative(_Element.prototype.appendChild);
  1660. }
  1661.  
  1662. // Function to catch and block various methods to open a new window with 3rd-party content.
  1663. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1664. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1665. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1666. // node or simply a link with piece of javascript code in the HREF attribute.
  1667. function preventPopups() {
  1668. // call sandbox-me if in iframe and not whitelisted
  1669. if (inIFrame) {
  1670. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1671. return;
  1672. }
  1673.  
  1674. scriptLander(() => {
  1675. let nt = new nullTools({log:true});
  1676. let open = (...args) => {
  1677. '[native code]';
  1678. console.warn('Site attempted to open a new window', ...args);
  1679. return {
  1680. document: nt.proxy({
  1681. write: nt.func({}, 'write'),
  1682. writeln: nt.func({}, 'writeln')
  1683. }),
  1684. location: nt.proxy({})
  1685. };
  1686. };
  1687.  
  1688. createWindowOpenWrapper(open);
  1689.  
  1690. console.log('Popup prevention enabled.');
  1691. }, nullTools, createWindowOpenWrapper);
  1692. }
  1693.  
  1694. // Helper function to close background tab if site opens itself in a new tab and then
  1695. // loads a 3rd-party page in the background one (thus performing background redirect).
  1696. function preventPopunders() {
  1697. // create "close_me" event to call high-level window.close()
  1698. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1699. let callClose = () => {
  1700. console.log('close call');
  1701. window.close();
  1702. };
  1703. window.addEventListener(eventName, callClose, true);
  1704.  
  1705. scriptLander(() => {
  1706. // get host of a provided URL with help of an anchor object
  1707. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1708. let parseURL = document.createElement('A');
  1709. let getHost = url => {
  1710. parseURL.href = url;
  1711. return parseURL.hostname
  1712. };
  1713. // site went to a new tab and attempts to unload
  1714. // call for high-level close through event
  1715. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1716. // check is URL local or goes to different site
  1717. let isLocal = (url) => {
  1718. if (url === location.pathname || url === location.href)
  1719. return true; // URL points to current pathname or full address
  1720. let host = getHost(url);
  1721. let site = location.hostname;
  1722. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1723. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1724. };
  1725.  
  1726. let _open = window.open.bind(window);
  1727. let open = (...args) => {
  1728. '[native code]';
  1729. let url = args[0];
  1730. if (url && isLocal(url))
  1731. window.addEventListener('beforeunload', closeWindow, true);
  1732. return _open(...args);
  1733. };
  1734.  
  1735. createWindowOpenWrapper(open);
  1736.  
  1737. console.log("Background redirect prevention enabled.");
  1738. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1739. }
  1740.  
  1741. // Mix between check for popups and popunders
  1742. // Significantly more agressive than both and can't be used as universal solution
  1743. function preventPopMix() {
  1744. if (inIFrame) {
  1745. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1746. return;
  1747. }
  1748.  
  1749. // create "close_me" event to call high-level window.close()
  1750. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1751. let callClose = () => {
  1752. console.log('close call');
  1753. window.close();
  1754. };
  1755. window.addEventListener(eventName, callClose, true);
  1756.  
  1757. scriptLander(() => {
  1758. let _open = window.open,
  1759. parseURL = document.createElement('A');
  1760. // get host of a provided URL with help of an anchor object
  1761. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1762. let getHost = (url) => {
  1763. parseURL.href = url;
  1764. return parseURL.host;
  1765. };
  1766. // site went to a new tab and attempts to unload
  1767. // call for high-level close through event
  1768. let closeWindow = () => {
  1769. _open(window.location,'_self');
  1770. window.dispatchEvent(new CustomEvent(eventName, {}));
  1771. };
  1772. // check is URL local or goes to different site
  1773. function isLocal(url) {
  1774. let loc = window.location;
  1775. if (url === loc.pathname || url === loc.href)
  1776. return true; // URL points to current pathname or full address
  1777. let host = getHost(url),
  1778. site = loc.host;
  1779. if (host === '')
  1780. return false; // URLs with unusual protocol may have empty 'host'
  1781. if (host.length > site.length)
  1782. [site, host] = [host, site];
  1783. return site.includes(host, site.length - host.length);
  1784. }
  1785.  
  1786. // add check for redirect for 5 seconds, then disable it
  1787. function checkRedirect() {
  1788. window.addEventListener('beforeunload', closeWindow, true);
  1789. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1790. }
  1791.  
  1792. function open(url, name) {
  1793. '[native code]';
  1794. if (url && isLocal(url) && (!name || name === '_blank')) {
  1795. console.warn('Suspicious local new window', arguments);
  1796. checkRedirect();
  1797. return _open.apply(this, arguments);
  1798. }
  1799. console.warn('Blocked attempt to open a new window', arguments);
  1800. return {
  1801. document: {
  1802. write: () => {},
  1803. writeln: () => {}
  1804. }
  1805. };
  1806. }
  1807.  
  1808. function clickHandler(e) {
  1809. let link = e.target,
  1810. url = link.href||'';
  1811. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1812. console.log('Link', link, 'were created dinamically, but looks fine.');
  1813. return true;
  1814. }
  1815. if (isLocal(url) && link.target === '_blank') {
  1816. console.log('Suspicious local link', link);
  1817. checkRedirect();
  1818. return;
  1819. }
  1820. console.log('Blocked suspicious click on a link', link);
  1821. e.stopPropagation();
  1822. e.preventDefault();
  1823. }
  1824.  
  1825. createWindowOpenWrapper(open, clickHandler);
  1826.  
  1827. console.log("Mixed popups prevention enabled.");
  1828. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  1829. }
  1830. // External listener for case when site known to open popups were loaded in iframe
  1831. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1832. // Some sites replace frame's window.location with data-url to run in clean context
  1833. if (!inIFrame) window.addEventListener(
  1834. 'message', function(e) {
  1835. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1836. return;
  1837. let src = e.data.href;
  1838. for (let frame of document.querySelectorAll('iframe'))
  1839. if (frame.contentWindow === e.source) {
  1840. if (frame.hasAttribute('sandbox')) {
  1841. if (!frame.sandbox.contains('allow-popups'))
  1842. return; // exit frame since it's already sandboxed and popups are blocked
  1843. // remove allow-popups if frame already sandboxed
  1844. frame.sandbox.remove('allow-popups');
  1845. } else
  1846. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1847. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1848. // but to apply content must be reloaded and this script will re-apply it in the result
  1849. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1850. console.log('Disallowed popups from iframe', frame);
  1851.  
  1852. // reload frame content to apply restrictions
  1853. if (!src) {
  1854. src = frame.src;
  1855. console.log('Unable to get current iframe location, reloading from src', src);
  1856. } else
  1857. console.log('Reloading iframe with URL', src);
  1858. frame.src = 'about:blank';
  1859. frame.src = src;
  1860. }
  1861. }, false
  1862. );
  1863.  
  1864. function selectiveEval() {
  1865. scriptLander(() => {
  1866. let nt = new nullTools();
  1867. let _eval = win.eval.bind(window);
  1868. nt.define(win, 'eval', function(...args) {
  1869. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  1870. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  1871. return null;
  1872. }
  1873. return _eval(...args);
  1874. });
  1875. }, nullTools);
  1876. }
  1877.  
  1878. // === Scripts for specific domains ===
  1879.  
  1880. let scripts = {};
  1881. // prevent popups and redirects block
  1882. // Popups
  1883. scripts.preventPopups = {
  1884. other: [
  1885. 'biqle.ru',
  1886. 'chaturbate.com',
  1887. 'dfiles.ru',
  1888. 'eporner.eu',
  1889. 'hentaiz.org',
  1890. 'mirrorcreator.com',
  1891. 'online-multy.ru',
  1892. 'radikal.ru', 'rumedia.ws',
  1893. 'thepiratebay.org',
  1894. 'unionpeer.com',
  1895. 'zippyshare.com'
  1896. ],
  1897. now: preventPopups
  1898. };
  1899. // Popunders (background redirect)
  1900. scripts.preventPopunders = {
  1901. other: [
  1902. 'lostfilm-online.ru',
  1903. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  1904. 'perfectgirls.net'
  1905. ],
  1906. now: preventPopunders
  1907. };
  1908. // PopMix (both types of popups encountered on site)
  1909. scripts['openload.co'] = {
  1910. other: ['oload.tv', 'oload.info'],
  1911. now: () => {
  1912. let nt = new nullTools();
  1913. nt.define(win, 'CNight', win.CoinHive);
  1914. if (location.pathname.startsWith('/embed/')) {
  1915. nt.define(win, 'BetterJsPop', {
  1916. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  1917. config: ((o) => console.warn('BetterJsPop.config', o)),
  1918. Browser: { isChrome: true }
  1919. });
  1920. nt.define(win, 'isSandboxed', nt.func(null));
  1921. nt.define(win, 'adblock', false);
  1922. nt.define(win, 'adblock2', false);
  1923. } else preventPopMix();
  1924. }
  1925. };
  1926. scripts['turbobit.net'] = preventPopMix;
  1927.  
  1928. scripts['tapochek.net'] = () => {
  1929. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  1930. let _appendChild = Object.getOwnPropertyDescriptor(_Node.prototype, 'appendChild');
  1931. let _appendChild_value = _appendChild.value;
  1932. _appendChild.value = function appendChild(node) {
  1933. if (this === win.document.body)
  1934. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  1935. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  1936. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  1937. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  1938. throw '...eenope!';
  1939. return _appendChild_value.apply(this, arguments);
  1940. };
  1941. Object.defineProperty(_Node.prototype, 'appendChild', _appendChild);
  1942.  
  1943. // disable window focus tricks and changing location
  1944. let focusHandlerName = /\WfocusAchieved\(/
  1945. let _toString = Function.prototype.toString;
  1946. let _setInterval = win.setInterval;
  1947. win.setInterval = (...args) => {
  1948. if (args.length && focusHandlerName.test(_toString.call(args[0]))) {
  1949. console.log('skip setInterval for', ...args);
  1950. return -1;
  1951. }
  1952. return _setInterval(...args);
  1953. };
  1954. let _addEventListener = win.addEventListener;
  1955. win.addEventListener = function(...args) {
  1956. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString.call(args[1]))) {
  1957. console.log('skip addEventListener for', ...args);
  1958. return void 0;
  1959. }
  1960. return _addEventListener.apply(this, args);
  1961. };
  1962.  
  1963. // generic popup prevention
  1964. preventPopups();
  1965. };
  1966.  
  1967. scripts['rustorka.com'] = {
  1968. other: ['rustorka.lib'],
  1969. now: () => scriptLander(() => {
  1970. let crumbler = () => {
  1971. // crumble suspicious cookies
  1972. let base = '=; expires=Thu, 01 Jan 1970 00:00:01 UTC; Max-Age=-99999999; path=/';
  1973. console.log('cookies', document.cookie);
  1974. for (let name of ['adblock', 'gophp', '_692293176245', '_692293176246'])
  1975. document.cookie = `${name}${base}`;
  1976. for (let name of ['st2', 'st3']) {
  1977. document.cookie = `${name}${base}forum`;
  1978. document.cookie = `${name}${base}forum/`;
  1979. }
  1980. console.log('cookies', document.cookie);
  1981. };
  1982. document.addEventListener('DOMContentLoaded', crumbler, false);
  1983. crumbler();
  1984.  
  1985. let nt = new nullTools({trace: true});
  1986. nt.define(win, 'syka', false);
  1987. nt.define(win, '_692293176244', location.href);
  1988. [
  1989. 'MTLuxup', 'MTAdSniper', 'MTutarg', 'MTUAatar', 'MTcityAds', 'MTmxMark',
  1990. 'MTmxMark2', 'MTmdnt', 'MTrfDumedia', 'MXsmTDS', 'MTritorno', 'MTadvice',
  1991. 'cyka', 'MTAdTraff', 'MTExebid', 'MXsockFound'
  1992. ].forEach(name => nt.define(win, name, nt.func(null, name)));
  1993. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  1994. if (!_eval_def)
  1995. return;
  1996. let _eval_val = _eval_def.value;
  1997. _eval_def.value = (...args) => {
  1998. if (args[0] && args[0].includes('antiadblock'))
  1999. return console.log('Anti-AdBlock script may run another day, but not today.');
  2000. return _eval_val.apply(this, args);
  2001. };
  2002. Object.defineProperty(win, 'eval', _eval_def);
  2003. win.open = (...args) => {
  2004. console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2005. location.replace(location.href);
  2006. return null;
  2007. };
  2008. window.addEventListener('DOMContentLoaded', () => {
  2009. let link = void 0;
  2010. document.body.addEventListener('mousedown', e => {
  2011. link = e.target.closest('a, select, #fancybox-title-wrap');
  2012. }, false);
  2013. let _open = window.open.bind(window);
  2014. let _getAttribute = _Element.prototype.getAttribute;
  2015. win.open = (...args) => {
  2016. let url = args[0];
  2017. if (link instanceof HTMLAnchorElement) {
  2018. // third-party post links
  2019. let href = _getAttribute.call(link, 'href');
  2020. if (link.classList.contains('postLink') &&
  2021. !link.matches(`a[href*="${location.hostname}"]`) &&
  2022. (href === url || link.href === url))
  2023. return _open(...args);
  2024. // onclick # links
  2025. if (href === '#' && /window\.open/.test(_getAttribute.call(link, 'onclick')))
  2026. return _open(...args);
  2027. // force local links to load in the current window
  2028. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2029. location.assign(href);
  2030. }
  2031. // list of image hostings under upload picture button (new comment)
  2032. if (link instanceof HTMLSelectElement &&
  2033. !url.includes(location.hostname) &&
  2034. link.value === url)
  2035. return _open(...args);
  2036. // open screenshot in a new window
  2037. if (link instanceof HTMLSpanElement &&
  2038. link.id === 'fancybox-title-wrap')
  2039. return _open(...args);
  2040. // looks like tabunder
  2041. if (link === null && url === location.href)
  2042. location.replace(url); // reload current page
  2043. // other cases
  2044. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2045. return {};
  2046. };
  2047. }, true);
  2048. }, nullTools)
  2049. };
  2050.  
  2051. // other
  2052. scripts['1tv.ru'] = () => scriptLander(() => {
  2053. let nt = new nullTools();
  2054. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2055. let disablePlugins = {
  2056. 'antiblock': false,
  2057. 'stat1tv': false
  2058. };
  2059. let _EUMPConfig = void 0;
  2060. let _EUMPConfig_set = x => {
  2061. if (x.plugins) {
  2062. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2063. console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2064. }
  2065. _EUMPConfig = x;
  2066. };
  2067. if ('EUMPConfig' in win)
  2068. _EUMPConfig_set(win.EUMPConfig);
  2069. Object.defineProperty(win, 'EUMPConfig', {
  2070. enumerable: true,
  2071. get: () => _EUMPConfig,
  2072. set: _EUMPConfig_set
  2073. });
  2074. }, nullTools);
  2075.  
  2076. scripts['2picsun.ru'] = {
  2077. other: [
  2078. 'pics2sun.ru', '3pics-img.ru'
  2079. ],
  2080. now: () => {
  2081. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2082. }
  2083. };
  2084.  
  2085. scripts['4pda.ru'] = {
  2086. now: () => {
  2087. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2088. let isForum = location.pathname.startsWith('/forum/'),
  2089. remove = node => (node && node.parentNode.removeChild(node)),
  2090. hide = node => (node && (node.style.display = 'none'));
  2091.  
  2092. // save links to non-overridden functions to use later
  2093. let protectedElems;
  2094. // protect/hide changed attributes in case site attempt to restore them
  2095. function styleProtector(eventMode) {
  2096. let _toLowerCase = String.prototype.toLowerCase,
  2097. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2098. protectedElems = new WeakMap();
  2099. function protoOverride(element, functionName, isStyleCheck, returnIfProtected) {
  2100. let originalFunction = element.prototype[functionName];
  2101. element.prototype[functionName] = function wrapper() {
  2102. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2103. return returnIfProtected(this, arguments);
  2104. return originalFunction.apply(this, arguments);
  2105. };
  2106. }
  2107. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2108. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2109. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2110. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2111. if (!eventMode)
  2112. return protectedElems;
  2113. let e = document.createEvent('Event');
  2114. e.initEvent('protoOverride', false, false);
  2115. window.protectedElems = protectedElems;
  2116. window.dispatchEvent(e);
  2117. }
  2118. if (!isFirefox)
  2119. protectedElems = styleProtector(false);
  2120. else {
  2121. let script = document.createElement('script');
  2122. script.textContent = `(${styleProtector.toString()})(true);`;
  2123. window.addEventListener(
  2124. 'protoOverride', function protoOverrideCallback() {
  2125. if (win.protectedElems) {
  2126. protectedElems = win.protectedElems;
  2127. delete win.protectedElems;
  2128. }
  2129. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2130. }, true
  2131. );
  2132. _appendChild(script);
  2133. _removeChild(script);
  2134. }
  2135.  
  2136. // clean a page
  2137. window.addEventListener(
  2138. 'DOMContentLoaded', function() {
  2139. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2140. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2141.  
  2142. HeaderAds: {
  2143. // hide ads above HEADER
  2144. let header = document.querySelector('.h-frame');
  2145. if (header)
  2146. header = header.parentNode;
  2147. for (let itm of header.parentNode.children)
  2148. if (itm !== header)
  2149. hide(itm);
  2150. else break;
  2151. }
  2152.  
  2153. if (isForum) {
  2154. let itm = document.querySelector('#logostrip');
  2155. if (itm)
  2156. remove(itm.parentNode.nextSibling);
  2157. // clear background in the download frame
  2158. if (location.pathname.startsWith('/forum/dl/')) {
  2159. let setBackground = node => _setAttribute.call(
  2160. node,
  2161. 'style', (_getAttribute.call(node, 'style') || '') +
  2162. ';background-color:#4ebaf6!important'
  2163. );
  2164. setBackground(document.body);
  2165. for (let itm of document.querySelectorAll('body > div'))
  2166. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2167. remove(itm);
  2168. else
  2169. setBackground(itm);
  2170. }
  2171. // exist from DOMContentLoaded since the rest is not for forum
  2172. return;
  2173. }
  2174.  
  2175. FixNavMenu: {
  2176. // restore DevDB link in the navigation
  2177. let itm = document.querySelector('#nav li a[href$="/devdb/"]')
  2178. if (itm) itm.closest('li').style.display = 'block';
  2179. // hide ad link from the navigation
  2180. hide(document.querySelector('#nav li a[data-dotrack]'));
  2181. }
  2182. SidebarAds: {
  2183. // remove ads from sidebar
  2184. let aside = document.querySelectorAll('section[id] > :first-child + :last-child');
  2185. if (!aside.length)
  2186. break SidebarAds;
  2187. let post;
  2188. for (let side of aside)
  2189. for (let itm of Array.from(side.children)) {
  2190. post = itm.classList.contains('post');
  2191. if (itm.querySelector('iframe') && !post)
  2192. remove(itm);
  2193. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2194. hide(itm);
  2195. }
  2196. }
  2197.  
  2198. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2199.  
  2200. let extra = 'background-image:none!important;background-color:transparent!important',
  2201. fakeStyles = new WeakMap(),
  2202. styleProxy = {
  2203. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2204. set: function(target, prop, value) {
  2205. let fakeStyle = fakeStyles.get(target);
  2206. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2207. return true;
  2208. }
  2209. };
  2210. for (let itm of document.querySelectorAll('[id]:not(A), A')) {
  2211. if (!(itm.offsetWidth > 0.95 * width() &&
  2212. itm.offsetHeight > 0.85 * height()))
  2213. continue;
  2214. if (itm.tagName !== 'A') {
  2215. fakeStyles.set(itm.style, {
  2216. 'backgroundImage': itm.style.backgroundImage,
  2217. 'backgroundColor': itm.style.backgroundColor
  2218. });
  2219.  
  2220. try {
  2221. Object.defineProperty(itm, 'style', {
  2222. value: new Proxy(itm.style, styleProxy),
  2223. enumerable: true
  2224. });
  2225. } catch (e) {
  2226. console.log('Unable to protect style property.', e);
  2227. }
  2228.  
  2229. if (protectedElems)
  2230. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2231.  
  2232. _setAttribute.call(itm, 'style', `${(_getAttribute.call(itm, 'style') || '')};${extra}`);
  2233. }
  2234. if (itm.tagName === 'A') {
  2235. if (protectedElems)
  2236. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2237. _setAttribute.call(itm, 'style', 'display:none!important');
  2238. }
  2239. }
  2240. }
  2241. );
  2242. }
  2243. };
  2244.  
  2245. scripts['adhands.ru'] = () => scriptLander(() => {
  2246. let nt = new nullTools();
  2247. try {
  2248. let _adv;
  2249. Object.defineProperty(win, 'adv', {
  2250. get: () => _adv,
  2251. set: (v) => {
  2252. console.log('Blocked advert on adhands.ru.');
  2253. nt.define(v, 'advert', '');
  2254. _adv = v;
  2255. }
  2256. });
  2257. } catch (ignore) {
  2258. if (!win.adv)
  2259. console.log('Unable to locate advert on adhands.ru.');
  2260. else {
  2261. console.log('Blocked advert on adhands.ru.');
  2262. nt.define(win.adv, 'advert', '');
  2263. }
  2264. }
  2265. }, nullTools);
  2266.  
  2267. scripts['all-episodes.tv'] = () => {
  2268. let nt = new nullTools();
  2269. nt.define(win, 'perX1', 2);
  2270. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2271. };
  2272.  
  2273. scripts['allhentai.ru'] = () => {
  2274. selectiveEval();
  2275. preventPopups();
  2276. scriptLander(() => {
  2277. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2278. if (!_onerror)
  2279. return;
  2280. _onerror.set = (...args) => console.log(args[0].toString());
  2281. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2282. });
  2283. };
  2284.  
  2285. scripts['allmovie.pro'] = {
  2286. other: ['rufilmtv.org'],
  2287. dom: function() {
  2288. // pretend to be Android to make site use different played for ads
  2289. if (isSafari)
  2290. return;
  2291. Object.defineProperty(navigator, 'userAgent', {
  2292. get: function(){
  2293. 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';
  2294. },
  2295. enumerable: true
  2296. });
  2297. }
  2298. };
  2299.  
  2300. scripts['anidub-online.ru'] = {
  2301. other: ['anime.anidub.com', 'online.anidub.com'],
  2302. dom: function() {
  2303. if (win.ogonekstart1)
  2304. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2305. },
  2306. now: () => createStyle([
  2307. '.background {background: none!important;}',
  2308. '.background > script + div,'+
  2309. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2310. '{display:none!important}'
  2311. ])
  2312. };
  2313.  
  2314. scripts['drive2.ru'] = () => {
  2315. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2316. scriptLander(() => {
  2317. let _d2 = void 0;
  2318. Object.defineProperty(win, 'd2', {
  2319. get: () => _d2,
  2320. set: o => {
  2321. _d2 = new Proxy(o, {
  2322. set: (tgt, prop, val) => {
  2323. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2324. val = () => null;
  2325. tgt[prop] = val;
  2326. }
  2327. });
  2328. }
  2329. });
  2330. });
  2331. };
  2332.  
  2333. scripts['fishki.net'] = () => {
  2334. scriptLander(() => {
  2335. let nt = new nullTools();
  2336. let fishki = {};
  2337. nt.define(fishki, 'adv', nt.proxy({
  2338. afterAdblockCheck: nt.func(null),
  2339. refreshFloat: nt.func(null)
  2340. }));
  2341. nt.define(fishki, 'is_adblock', false);
  2342. nt.define(win, 'fishki', fishki);
  2343. }, nullTools);
  2344. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2345. };
  2346.  
  2347. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2348.  
  2349. scripts['hdgo.cc'] = {
  2350. other: ['46.30.43.38', 'couber.be'],
  2351. now: () => (new MutationObserver(
  2352. (ms) => {
  2353. let m, node;
  2354. for (m of ms) for (node of m.addedNodes)
  2355. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2356. node.removeAttribute('onerror');
  2357. }
  2358. )).observe(document.documentElement, { childList:true, subtree: true })
  2359. };
  2360.  
  2361. scripts['gismeteo.ru'] = {
  2362. other: ['gismeteo.ua'],
  2363. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2364. };
  2365.  
  2366. scripts['hdrezka.ag'] = () => {
  2367. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2368. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2369. };
  2370.  
  2371. scripts['hideip.me'] = {
  2372. now: () => scriptLander(() => {
  2373. let _innerHTML = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML');
  2374. let _set_innerHTML = _innerHTML.set;
  2375. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2376. let _get_innerText = _innerText.get;
  2377. let div = document.createElement('div');
  2378. _innerHTML.set = function(...args) {
  2379. _set_innerHTML.call(div, args[0].replace('i','a'));
  2380. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2381. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2382. console.log('Anti-Adblock killed.');
  2383. return true;
  2384. }
  2385. _set_innerHTML.apply(this, args);
  2386. };
  2387. Object.defineProperty(_Element.prototype, 'innerHTML', _innerHTML);
  2388. Object.defineProperty(win, 'adblock', {
  2389. get: () => false,
  2390. set: () => null,
  2391. enumerable: true
  2392. });
  2393. let _$ = {};
  2394. let _$_map = new WeakMap();
  2395. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2396. let _val_gOPD = _gOPD.value;
  2397. _gOPD.value = function(...args) {
  2398. let _res = _val_gOPD.apply(this, args);
  2399. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2400. delete _res.get;
  2401. delete _res.set;
  2402. _res.value = win[args[1]];
  2403. }
  2404. return _res;
  2405. };
  2406. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2407. let getJQWrap = (n) => {
  2408. let name = n;
  2409. return {
  2410. enumerable: true,
  2411. get: () => _$[name],
  2412. set: x => {
  2413. if (_$_map.has(x)) {
  2414. _$[name] = _$_map.get(x);
  2415. return true;
  2416. }
  2417. if (x === _$.$ || x === _$.jQuery) {
  2418. _$[name] = x;
  2419. return true;
  2420. }
  2421. _$[name] = new Proxy(x, {
  2422. apply: (t, o, args) => {
  2423. let _res = t.apply(o, args);
  2424. if (_$_map.has(_res.is))
  2425. _res.is = _$_map.get(_res.is);
  2426. else {
  2427. let _is = _res.is;
  2428. _res.is = function(...args) {
  2429. if (args[0] === ':hidden')
  2430. return false;
  2431. return _is.apply(this, args);
  2432. };
  2433. _$_map.set(_is, _res.is);
  2434. }
  2435. return _res;
  2436. }
  2437. });
  2438. _$_map.set(x, _$[name]);
  2439. return true;
  2440. }
  2441. };
  2442. };
  2443. Object.defineProperty(win, '$', getJQWrap('$'));
  2444. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2445. let _dP = Object.defineProperty;
  2446. Object.defineProperty = function(...args) {
  2447. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2448. return void 0;
  2449. return _dP.apply(this, args);
  2450. };
  2451. })
  2452. };
  2453.  
  2454. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2455. let nt = new nullTools();
  2456. /*jslint evil: true */ // yes, evil, I know
  2457. let _write = document.write.bind(document);
  2458. /*jslint evil: false */
  2459. nt.define(document, 'write', t => {
  2460. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2461. if (id && id[1])
  2462. return _write(`<div id="${id[1]}"></div>${t}`);
  2463. return _write('');
  2464. });
  2465. });
  2466.  
  2467. scripts['imageban.ru'] = {
  2468. now: () => {
  2469. Object.defineProperty(win, 'V7x1J', { get: () => null });
  2470. //preventPopunders();
  2471. }
  2472. };
  2473.  
  2474. scripts['kinopoisk.ru'] = {
  2475. now: () => {
  2476. // set no-branding body style
  2477. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2478. },
  2479. dom: () => {
  2480. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  2481. )(_de.querySelector('#branding-style'));
  2482. }
  2483. };
  2484.  
  2485. scripts['korrespondent.net'] = {
  2486. now: () => scriptLander(() => {
  2487. let nt = new nullTools();
  2488. nt.define(win, 'holder', function(id) {
  2489. let div = document.getElementById(id);
  2490. if (!div)
  2491. return;
  2492. if (div.parentNode.classList.contains('col__sidebar')) {
  2493. div.parentNode.appendChild(div);
  2494. div.style.height = '300px';
  2495. }
  2496. });
  2497. }, nullTools),
  2498. dom: () => {
  2499. for (let frame of document.querySelectorAll('.unit-side-informer > iframe'))
  2500. frame.parentNode.style.width = '1px';
  2501. }
  2502. };
  2503.  
  2504. scripts['mail.ru'] = () => scriptLander(() => {
  2505. let nt = new nullTools();
  2506. // Trick to prevent mail.ru from removing 3rd-party styles
  2507. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2508. // Disable some of their counters
  2509. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2510. if (location.hostname !== 'e.mail.ru')
  2511. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2512. else
  2513. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2514.  
  2515. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2516. function defineLocator(root) {
  2517. let _locator;
  2518. let fishnet = {
  2519. apply: (target, thisArg, args) => {
  2520. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2521. return target.apply(thisArg, args);
  2522. }
  2523. };
  2524.  
  2525. function wrapLocator(locator) {
  2526. if ('setup' in locator) {
  2527. let _setup = locator.setup;
  2528. locator.setup = function(o) {
  2529. if ('enable' in o) {
  2530. o.enable = false;
  2531. console.log('Disable mimic mode.');
  2532. }
  2533. if ('links' in o) {
  2534. o.links = [];
  2535. console.log('Call with empty list of sheets.');
  2536. }
  2537. return _setup.call(this, o);
  2538. };
  2539. locator.insertSheet = () => console.log('Ignore insertSheet.');
  2540. locator.wrap = () => console.log('Ignore wrap.');
  2541. }
  2542. try {
  2543. let names = [];
  2544. for (let name in locator)
  2545. if (locator[name] instanceof Function) {
  2546. locator[name]._name = name;
  2547. locator[name] = new Proxy(locator[name], fishnet);
  2548. names.push(name);
  2549. }
  2550. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  2551. } catch(e) {
  2552. console.log(e);
  2553. }
  2554. _locator = locator;
  2555. }
  2556.  
  2557. if ('locator' in root && root.locator) {
  2558. console.log('Found existing "locator" object. :|');
  2559. _locator = root.locator;
  2560. wrapLocator(root.locator);
  2561. }
  2562.  
  2563. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  2564. if (!loc_desc || loc_desc.set !== wrapLocator)
  2565. try {
  2566. Object.defineProperty(root, 'locator', {
  2567. set: wrapLocator,
  2568. get: () => _locator
  2569. });
  2570. } catch (err) {
  2571. console.log('Unable to redefine "locator" object!!!', err);
  2572. }
  2573. }
  2574.  
  2575. function defineDetector(mr) {
  2576. let __ = mr._ || {};
  2577.  
  2578. if ('HONEYPOT' in __) {
  2579. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  2580. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  2581. nt.define(__, 'STUCK_IN_POT', false);
  2582. }
  2583.  
  2584. __ = new Proxy(__, {
  2585. get: (t, p) => t[p],
  2586. set: (t, p, v) => {
  2587. console.log(`mr._.${p} =`, v);
  2588. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  2589. console.log('Not changed.');
  2590. t[p] = v; // setter in nt.define will prevent this when needed
  2591. return true;
  2592. }
  2593. });
  2594. Object.defineProperty(mr, '_', {
  2595. enumerable: true,
  2596. value: __
  2597. });
  2598. }
  2599.  
  2600. if (location.hostname === 'e.mail.ru')
  2601. defineLocator(win);
  2602. else
  2603. try {
  2604. let _mr;
  2605. Object.defineProperty(win, 'mr', {
  2606. enumerable: true,
  2607. get: () => _mr,
  2608. set: (v) => {
  2609. if (v === _mr)
  2610. return true;
  2611. console.log('Trapped new "mr" object.');
  2612. defineLocator(v.mimic ? v.mimic : v);
  2613. defineDetector(v);
  2614. _mr = v;
  2615. }
  2616. });
  2617. if (!('mr' in win))
  2618. throw 'Wat!?';
  2619. } catch (e) {
  2620. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  2621. defineLocator(win.mr);
  2622. defineDetector(win.mr);
  2623. }
  2624. }, nullTools);
  2625.  
  2626. scripts['megogo.net'] = {
  2627. now: () => {
  2628. let nt = new nullTools();
  2629. nt.define(win, 'adBlock', false);
  2630. nt.define(win, 'showAdBlockMessage', nt.func(null));
  2631. }
  2632. };
  2633.  
  2634. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  2635.  
  2636. scripts['overclockers.ru'] = {
  2637. now: () => scriptLander(() => {
  2638. let _innerHTML = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML');
  2639. let _set_innerHTML = _innerHTML.set;
  2640. _innerHTML.set = function() {
  2641. if (this === document.body) {
  2642. console.log('Anti-Adblock killed.');
  2643. return true;
  2644. }
  2645. _set_innerHTML.apply(this, arguments);
  2646. };
  2647. Object.defineProperty(_Element.prototype, 'innerHTML', _innerHTML);
  2648. }),
  2649. dom: () => scriptLander(() => {
  2650. let killed = () => console.log('Anti-Adblock killed.');
  2651. if ('$' in win)
  2652. win.$ = new Proxy($, {
  2653. apply: (tgt, that, args) => {
  2654. let res = tgt.apply(that, args);
  2655. if (res[0] && res[0] === document.body) {
  2656. res.html = () => killed;
  2657. res.empty = () => killed;
  2658. }
  2659. return res;
  2660. }
  2661. });
  2662. })
  2663. };
  2664. scripts['forums.overclockers.ru'] = {
  2665. now: () => {
  2666. createStyle('.needblock {position: fixed; left: -10000px}');
  2667. Object.defineProperty(win, 'adblck', {
  2668. get: () => 'no',
  2669. set: () => undefined,
  2670. enumerable: true
  2671. });
  2672. }
  2673. };
  2674.  
  2675. scripts['pb.wtf'] = {
  2676. other: ['piratbit.org', 'piratbit.ru'],
  2677. dom: () => {
  2678. // line above topic content and images in the slider in the header
  2679. let remove = node => (console.log('removed', node), node.parentNode.removeChild(node));
  2680. for (let el of document.querySelectorAll('.release-navbar a, #page_content a'))
  2681. if (location.hostname === el.hostname &&
  2682. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname))
  2683. remove(el.closest('div, tr'));
  2684. // casino ad button in random places
  2685. for (let el of document.querySelectorAll('.btn-group')) {
  2686. el = el.parentNode.parentNode;
  2687. if (el.tagName === 'TH')
  2688. remove(el);
  2689. }
  2690. // ads in comments
  2691. let el = document.querySelector('tbody[id^="post_"] + tbody:not([id])');
  2692. if (el && el.parentNode.children[2] == el)
  2693. remove(el);
  2694. }
  2695. };
  2696.  
  2697. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  2698.  
  2699. scripts['peka2.tv'] = () => {
  2700. let bodyClass = 'body--branding';
  2701. let checkNode = node => {
  2702. for (let className of node.classList)
  2703. if (className.includes('banner') || className === bodyClass) {
  2704. _removeAttribute.call(node, 'style');
  2705. node.classList.remove(className);
  2706. for (let attr of Array.from(node.attributes))
  2707. if (attr.name.startsWith('advert'))
  2708. _removeAttribute.call(node, attr.name);
  2709. }
  2710. };
  2711. (new MutationObserver(ms => {
  2712. let m, node;
  2713. for (m of ms) for (node of m.addedNodes)
  2714. if (node instanceof HTMLElement)
  2715. checkNode(node);
  2716. })).observe(_de, {childList: true, subtree: true});
  2717. (new MutationObserver(ms => {
  2718. for (let m of ms)
  2719. checkNode(m.target);
  2720. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  2721. };
  2722.  
  2723. scripts['qrz.ru'] = {
  2724. now: () => {
  2725. let nt = new nullTools();
  2726. nt.define(win, 'ab', false);
  2727. nt.define(win, 'tryMessage', nt.func(null));
  2728. }
  2729. };
  2730.  
  2731. scripts['razlozhi.ru'] = {
  2732. now: () => {
  2733. for (let func of ['createShadowRoot', 'attachShadow'])
  2734. if (func in _Element.prototype)
  2735. _Element.prototype[func] = function(){
  2736. return this.cloneNode();
  2737. };
  2738. }
  2739. };
  2740.  
  2741. scripts['rbc.ru'] = {
  2742. dom: () => {
  2743. let _preventDefault = Event.prototype.preventDefault;
  2744. Event.prototype.preventDefault = function preventDefault() {
  2745. let t = this.target;
  2746. if (t instanceof HTMLAnchorElement || t.closest('A'))
  2747. throw new Error('an.yandex redirect prevention');
  2748. return _preventDefault.call(this);
  2749. };
  2750.  
  2751. function cleaner(nodes) {
  2752. for (let node of nodes) {
  2753. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  2754. continue;
  2755. node.classList.remove('js-yandex-counter');
  2756. node.removeAttribute('data-yandex-name');
  2757. node.removeAttribute('data-yandex-params');
  2758. }
  2759. }
  2760. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  2761.  
  2762. (new MutationObserver(
  2763. ms => {
  2764. for (let m of ms) cleaner(m.addedNodes);
  2765. }
  2766. )).observe(_de, {childList: true, subtree: true});
  2767. }
  2768. };
  2769.  
  2770. scripts['rp5.ru'] = {
  2771. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  2772. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  2773. };
  2774.  
  2775. scripts['rutube.ru'] = () => scriptLander(() => {
  2776. let _parse = JSON.parse;
  2777. let _skip_enabled = false;
  2778. JSON.parse = (...args) => {
  2779. let res = _parse(...args),
  2780. log = false;
  2781. if (!res)
  2782. return res;
  2783. // parse player configuration
  2784. if ('appearance' in res || 'video_balancer' in res) {
  2785. log = true;
  2786. if (res.appearance) {
  2787. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  2788. res.appearance.forbid_seek = false;
  2789. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  2790. res.appearance.forbid_timeline_preview = false;
  2791. }
  2792. _skip_enabled = !!res.remove_unseekable_blocks;
  2793. //res.advert = [];
  2794. delete res.advert;
  2795. //for (let limit of res.limits)
  2796. // limit.limit = 0;
  2797. delete res.limits;
  2798. //res.yast = null;
  2799. //res.yast_live_online = null;
  2800. delete res.yast;
  2801. delete res.yast_live_online;
  2802. Object.defineProperty(res, 'stat', {
  2803. get: () => [],
  2804. set: () => true,
  2805. enumerable: true
  2806. });
  2807. }
  2808.  
  2809. // parse video configuration
  2810. if ('video_url' in res) {
  2811. log = true;
  2812. if (res.cuepoints && !_skip_enabled)
  2813. for (let point of res.cuepoints) {
  2814. point.is_pause = false;
  2815. point.show_navigation = true;
  2816. point.forbid_seek = false;
  2817. }
  2818. }
  2819.  
  2820. if (log)
  2821. console.log('[rutube]', res);
  2822. return res;
  2823. };
  2824. });
  2825.  
  2826. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  2827. let _addEventListener = Object.getPrototypeOf(HTMLDocument).prototype.addEventListener;
  2828. document.addEventListener = function(event, callback) {
  2829. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  2830. return;
  2831. return _addEventListener.apply(this, arguments);
  2832. };
  2833. });
  2834.  
  2835. scripts['spaces.ru'] = () => {
  2836. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  2837. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  2838. };
  2839.  
  2840. scripts['spam-club.blogspot.co.uk'] = () => {
  2841. let _clientHeight = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientHeight'),
  2842. _clientWidth = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientWidth');
  2843. let wrapGetter = (getter) => {
  2844. let _getter = getter;
  2845. return function() {
  2846. let _size = _getter.apply(this, arguments);
  2847. return _size ? _size : 1;
  2848. };
  2849. };
  2850. _clientHeight.get = wrapGetter(_clientHeight.get);
  2851. _clientWidth.get = wrapGetter(_clientWidth.get);
  2852. Object.defineProperty(_Element.prototype, 'clientHeight', _clientHeight);
  2853. Object.defineProperty(_Element.prototype, 'clientWidth', _clientWidth);
  2854. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  2855. _set_onload = _onload.set;
  2856. _onload.set = function() {
  2857. if (this instanceof HTMLImageElement)
  2858. return true;
  2859. _set_onload.apply(this, arguments);
  2860. };
  2861. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  2862. };
  2863.  
  2864. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  2865.  
  2866. scripts['sports.ru'] = {
  2867. now: () => {
  2868. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  2869. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  2870. // extra functionality: shows/hides panel at the top depending on scroll direction
  2871. createStyle([
  2872. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  2873. '.user-panel-up { top: -40px!important }'
  2874. ], {id: 'userPanelSlide'}, false);
  2875. },
  2876. dom: () => {
  2877. (function lookForPanel() {
  2878. let panel = document.querySelector('.user-panel__fixed');
  2879. if (!panel)
  2880. setTimeout(lookForPanel, 100);
  2881. else
  2882. window.addEventListener(
  2883. 'wheel', function(e) {
  2884. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  2885. panel.classList.add('user-panel-up');
  2886. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  2887. panel.classList.remove('user-panel-up');
  2888. }, false
  2889. );
  2890. })();
  2891. }
  2892. };
  2893.  
  2894. scripts['stealthz.ru'] = {
  2895. dom: () => {
  2896. // skip timeout
  2897. let $ = document.querySelector.bind(document);
  2898. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  2899. if (!timer_1 || !timer_2)
  2900. return;
  2901. timer_1.style.display = 'none';
  2902. timer_2.style.display = 'block';
  2903. }
  2904. };
  2905.  
  2906. scripts['yap.ru'] = {
  2907. other: ['yaplakal.com'],
  2908. now: () => {
  2909. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  2910. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  2911. }
  2912. };
  2913.  
  2914. scripts['rambler.ru'] = {
  2915. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  2916. now: () => scriptLander(() => {
  2917. // Prevent autoplay
  2918. if (!('EaglePlayer' in win)) {
  2919. let _EaglePlayer = void 0;
  2920. Object.defineProperty(win, 'EaglePlayer', {
  2921. enumerable: true,
  2922. get: () => _EaglePlayer,
  2923. set: x => {
  2924. if (x === _EaglePlayer)
  2925. return true;
  2926. _EaglePlayer = new Proxy(x, {
  2927. construct: (targ, args) => {
  2928. let player = new targ(...args);
  2929. if (!player.options) {
  2930. console.log('EaglePlayer: no options', EaglePlayer);
  2931. return player;
  2932. }
  2933. Object.defineProperty(player.options, 'autoplay', {
  2934. get: () => false,
  2935. set: () => true
  2936. });
  2937. Object.defineProperty(player.options, 'scroll', {
  2938. get: () => false,
  2939. set: () => true
  2940. });
  2941. return player;
  2942. }
  2943. });
  2944. }
  2945. });
  2946. let _setAttribute = _Element.prototype.setAttribute;
  2947. let isAutoplay = /^autoplay$/i;
  2948. _Element.prototype.setAttribute = function setAttribute(name) {
  2949. if (!this._stopped && isAutoplay.test(name)) {
  2950. console.log('Prevented assigning autoplay attribute.');
  2951. return null;
  2952. }
  2953. return _setAttribute.apply(this, arguments);
  2954. };
  2955. } else {
  2956. console.log('EaglePlayer function already exists.');
  2957. if (inIFrame) {
  2958. let _setAttribute = _Element.prototype.setAttribute;
  2959. let isAutoplay = /^autoplay$/i;
  2960. _Element.prototype.setAttribute = function setAttribute(name) {
  2961. if (!this._stopped && isAutoplay.test(name)) {
  2962. console.log('Prevented assigning autoplay attribute.');
  2963. this._stopped = true;
  2964. this.play = () => {
  2965. console.log('Prevented attempt to force-start playback.');
  2966. delete this.play;
  2967. };
  2968. return null;
  2969. }
  2970. return _setAttribute.apply(this, arguments);
  2971. };
  2972. }
  2973. }
  2974. if (location.hostname.endsWith('.media.eagleplatform.com'))
  2975. return;
  2976. // prevent ads from loading
  2977. let blockObfuscated = false;
  2978. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  2979. let fts = Function.prototype.toString;
  2980. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  2981. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  2982. let _cssText_get = _cssText.get;
  2983. _cssText.configurable = false;
  2984. _cssText.get = function() {
  2985. let cssText = _cssText_get.call(this);
  2986. if (cssText.includes('content:')) {
  2987. console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  2988. blockObfuscated = true;
  2989. return null;
  2990. }
  2991. return cssText;
  2992. };
  2993. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  2994. let _setTimeout = win.setTimeout;
  2995. win.setTimeout = function(f) {
  2996. if (blockObfuscated && obfuscation.test(fts.call(f))) {
  2997. console.warn('Stopped setTimeout for:', fts.call(f).slice(0,100), '\u2026');
  2998. return null;
  2999. };
  3000. return _setTimeout.apply(this, arguments);
  3001. };
  3002. // fake global Adf object
  3003. let nt = new nullTools();
  3004. let Adf_banner = {};
  3005. [
  3006. 'reloadssp', 'sspScroll',
  3007. 'sspRich', 'ssp'
  3008. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3009. nt.define(win, 'Adf', nt.proxy({
  3010. banner: nt.proxy(Adf_banner)
  3011. }));
  3012. // extra script to remove partner news on gazeta.ru
  3013. if (!location.hostname.includes('gazeta.ru'))
  3014. return;
  3015. (new MutationObserver(
  3016. (ms) => {
  3017. let m, node, header;
  3018. for (m of ms) for (node of m.addedNodes)
  3019. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3020. header = node.querySelector('.sausage-header');
  3021. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3022. node.style.display = 'none';
  3023. }
  3024. }
  3025. )).observe(document.documentElement, { childList:true, subtree: true });
  3026. }, `let inIFrame = ${inIFrame}`, nullTools)
  3027. };
  3028.  
  3029. scripts['reactor.cc'] = {
  3030. other: ['joyreactor.cc', 'pornreactor.cc'],
  3031. now: () => {
  3032. selectiveEval();
  3033. scriptLander(() => {
  3034. let nt = new nullTools();
  3035. win.open = function(){
  3036. throw new Error('Redirect prevention.');
  3037. };
  3038. nt.define(win, 'Worker', function(){});
  3039. nt.define(win, 'JRCH', win.CoinHive);
  3040. }, nullTools);
  3041. },
  3042. click: function(e) {
  3043. let node = e.target;
  3044. if (node.nodeType === _Node.ELEMENT_NODE &&
  3045. node.style.position === 'absolute' &&
  3046. node.style.zIndex > 0)
  3047. node.parentNode.removeChild(node);
  3048. },
  3049. dom: function() {
  3050. let words = new RegExp(
  3051. 'блокировщик рекламы'
  3052. .split('')
  3053. .map(function(e){
  3054. return e+'[\u200b\u200c\u200d]*';
  3055. })
  3056. .join('')
  3057. .replace(' ', '\\s*')
  3058. .replace(/[аоре]/g, function(e){
  3059. return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];
  3060. }),
  3061. 'i'),
  3062. can;
  3063. function deeper(spider) {
  3064. for (let child of spider.childNodes)
  3065. if (words.test(child.innerText))
  3066. if (child.offsetHeight >= 750)
  3067. deeper(child);
  3068. else
  3069. can.push(child);
  3070. }
  3071. function probe() {
  3072. can = [];
  3073. deeper(document.body);
  3074. for (let spider of can)
  3075. _setAttribute.call(spider, 'style', 'background:none!important');
  3076. }
  3077. (new MutationObserver(probe))
  3078. .observe(document, { childList:true, subtree:true });
  3079. }
  3080. };
  3081.  
  3082. scripts['auto.ru'] = () => {
  3083. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3084. let userAdsListAds = (
  3085. '.listing-list > .listing-item,'+
  3086. '.listing-item_type_fixed.listing-item'
  3087. );
  3088. let catalogAds = (
  3089. 'div[class*="layout_catalog-inline"],'+
  3090. 'div[class$="layout_horizontal"]'
  3091. );
  3092. let otherAds = (
  3093. '.advt_auto,'+
  3094. '.sidebar-block,'+
  3095. '.pager-listing + div[class],'+
  3096. '.card > div[class][style],'+
  3097. '.sidebar > div[class],'+
  3098. '.main-page__section + div[class],'+
  3099. '.listing > tbody'
  3100. );
  3101. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3102. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3103. gardener(otherAds, words);
  3104. };
  3105.  
  3106. scripts['rsload.net'] = {
  3107. load: () => {
  3108. let dis = document.querySelector('label[class*="cb-disable"]');
  3109. if (dis)
  3110. dis.click();
  3111. },
  3112. click: e => {
  3113. let t = e.target;
  3114. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3115. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3116. }
  3117. };
  3118.  
  3119. let domain;
  3120. // add alternative domain names if present and wrap functions into objects
  3121. for (let name in scripts) {
  3122. if (scripts[name] instanceof Function)
  3123. scripts[name] = { now: scripts[name] };
  3124. for (domain of (scripts[name].other||[])) {
  3125. if (domain in scripts)
  3126. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3127. scripts[domain] = scripts[name];
  3128. }
  3129. delete scripts[name].other;
  3130. }
  3131. // look for current domain in the list and run appropriate code
  3132. domain = document.domain;
  3133. while (domain.indexOf('.') > -1) {
  3134. if (domain in scripts) for (let when in scripts[domain])
  3135. switch(when) {
  3136. case 'now':
  3137. scripts[domain][when]();
  3138. break;
  3139. case 'dom':
  3140. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3141. break;
  3142. default:
  3143. document.addEventListener (when, scripts[domain][when], false);
  3144. }
  3145. domain = domain.slice(domain.indexOf('.') + 1);
  3146. }
  3147.  
  3148. // Batch script lander
  3149. if (!skipLander)
  3150. landScript(batchLand, batchPrepend);
  3151.  
  3152. { // JS Fixes Tools Menu
  3153. let openOptions = function() {
  3154. let ovl = _createElement('div'),
  3155. inner = _createElement('div');
  3156. ovl.style = (
  3157. 'position: fixed;'+
  3158. 'top:0; left:0;'+
  3159. 'bottom: 0; right: 0;'+
  3160. 'background: rgba(0,0,0,0.85);'+
  3161. 'z-index: 2147483647;'+
  3162. 'padding: 5em'
  3163. );
  3164. inner.style = (
  3165. 'background: whitesmoke;'+
  3166. 'font-size: 10pt;'+
  3167. 'color: black;'+
  3168. 'padding: 1em'
  3169. );
  3170. inner.textContent = 'JS Fixes Tools';
  3171. inner.appendChild(_createElement('br'));
  3172. inner.appendChild(_createElement('br'));
  3173. ovl.addEventListener(
  3174. 'click', function(e) {
  3175. if (e.target === ovl) {
  3176. ovl.parentNode.removeChild(ovl);
  3177. e.preventDefault();
  3178. }
  3179. e.stopPropagation();
  3180. }, false
  3181. );
  3182.  
  3183. let sObjBtn = _createElement('button');
  3184. sObjBtn.onclick = getStrangeObjectsList;
  3185. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  3186. inner.appendChild(_createElement('br'));
  3187. inner.appendChild(sObjBtn);
  3188.  
  3189. document.body.appendChild(ovl);
  3190. ovl.appendChild(inner);
  3191. };
  3192.  
  3193. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  3194. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  3195. document.addEventListener(
  3196. 'keydown', function(e) {
  3197. if ((e.code === opKey[opPos] || e.location) &&
  3198. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  3199. opPos += e.location ? 0 : 1;
  3200. e.stopPropagation();
  3201. e.preventDefault();
  3202. } else
  3203. opPos = 0;
  3204. if (opPos === opKey.length) {
  3205. opPos = 0;
  3206. openOptions();
  3207. }
  3208. }, false
  3209. );
  3210. }
  3211. })();