RU AdList JS Fixes

try to take over the world!

当前为 2018-10-31 提交的版本,查看 最新版本

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