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.2
  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. let _Object = root.Object,
  1448. _Function = root.Function,
  1449. _getOwnPropertyDescriptor = _Object.getOwnPropertyDescriptor;
  1450. onerror: {
  1451. // 'onerror' handler for scripts from blacklisted sources
  1452. let scriptMap = new WeakMap();
  1453. let _Reflect_apply = root.Reflect.apply,
  1454. _HTMLScriptElement = root.HTMLScriptElement,
  1455. _HTMLImageElement = root.HTMLImageElement;
  1456. let _get_tagName = _Function.prototype.call.bind(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1457. _get_scr_src = _Function.prototype.call.bind(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1458. _get_img_src = _Function.prototype.call.bind(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1459. let _get_src = node => {
  1460. if (node instanceof _HTMLScriptElement)
  1461. return _get_scr_src(node);
  1462. if (node instanceof _HTMLImageElement)
  1463. return _get_img_src(node);
  1464. return void 0
  1465. };
  1466. let _onerror = _Object.getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1467. _set_onerror = _Function.prototype.call.bind(_onerror.set);
  1468. _onerror.get = function() {
  1469. return scriptMap.get(this) || null;
  1470. };
  1471. _onerror.set = function(callback) {
  1472. if (typeof callback !== 'function') {
  1473. scriptMap.delete(this);
  1474. _set_onerror(this, callback);
  1475. return;
  1476. }
  1477. scriptMap.set(this, callback);
  1478. _set_onerror(this, function() {
  1479. let src = _get_src(this);
  1480. if (isBlocked(src)) {
  1481. console.warn(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1482. return;
  1483. }
  1484. _Reflect_apply(scriptMap.get(this), this, arguments);
  1485. });
  1486. };
  1487. _Object.defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1488. }
  1489. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1490. WSWrap: {
  1491. if (/Maxthon/.test(navigator.appVersion) ||
  1492. 'InstallTrigger' in win && 'StopIteration' in win) {
  1493. let _ws = Object.getOwnPropertyDescriptor(root, 'WebSocket');
  1494. if (!_ws)
  1495. break WSWrap;
  1496. _ws.value = new Proxy(_ws.value, {
  1497. construct: (ws, args) => {
  1498. if (isBlocked(args[0])) {
  1499. console.log('Blocked WS connection:', args[0]);
  1500. return {};
  1501. }
  1502. return new ws(...args);
  1503. }
  1504. });
  1505. Object.defineProperty(root, 'WebSocket', _ws);
  1506. }
  1507. }
  1508. untrustedClick: {
  1509. // TODO: try to rewrite this without wrapping createELement
  1510. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1511. // event on a newly created anchor with _blank target. Untrusted events must not open a new window.
  1512. let _createElement = _Function.prototype.call.bind(_Document.prototype.createElement),
  1513. _addEventListener = _Function.prototype.call.bind(root.EventTarget.prototype.addEventListener),
  1514. _HTMLAnchorElement = root.HTMLAnchorElement;
  1515. _Document.prototype.createElement = function createElement(...args) {
  1516. let el = _createElement(this, ...args);
  1517. if (el instanceof _HTMLAnchorElement)
  1518. _addEventListener(el, 'click', e => {
  1519. if (!e.isTrusted && e.target && !e.target.parentNode && e.target.target[0] === '_') {
  1520. e.stopPropagation();
  1521. e.preventDefault();
  1522. console.log('Blocked untrusted click on parentless anchor:', e.target);
  1523. }
  1524. }, false);
  1525.  
  1526. return el;
  1527. };
  1528. let doc_proto = Object.getPrototypeOf(root.document);
  1529. if (doc_proto && doc_proto.createElement !== _Document.prototype.createElement)
  1530. doc_proto.createElement = _Document.prototype.createElement;
  1531. }
  1532. // XHR Wrapper
  1533. let _proto = void 0;
  1534. try {
  1535. _proto = root.XMLHttpRequest.prototype;
  1536. } catch(ignore) {
  1537. return;
  1538. };
  1539. // blacklist of third-party domains requests to which are ignored
  1540. let blacklist = /[/.@](amgload\.net|dsn-fishki\.ru|kingoablc\.com|klcheck\.com|piguiqproxy\.com|rcdn\.pro|smcheck\.org|zmctrack\.net)([:/]|$)/i;
  1541. // blacklist of domains where all third-party requests are ignored
  1542. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1543. // highly suspicious URLs
  1544. let suspicious = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1545. let on_get_ban = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+)$/i;
  1546. let on_post_ban = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1547. let yandex_direct = /^https?:\/\/(yandex(\.[a-z]{2,3}){1,2}\/(images\/[a-z0-9/_-]{40,}|j?clck\/.*)|[^.]+\.yandex\.net\/static\/main\.js(\?.*)?)$/i;
  1548.  
  1549. function checkRequest(fname, method, url) {
  1550. if (blacklist.test(url) ||
  1551. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1552. method === 'GET' && on_get_ban.test(url) ||
  1553. method === 'POST' && on_post_ban.test(url) ||
  1554. yandex_direct.test(url)) {
  1555. console.log(`Blocked ${fname} ${method} request:`, url);
  1556. return true;
  1557. }
  1558. if (suspicious.test(url))
  1559. console.warn(`Suspicious ${fname} ${method} request:`, url);
  1560. return false;
  1561. }
  1562.  
  1563. let xhrStopList = new WeakSet();
  1564. let _open = root.Function.prototype.apply.bind(_proto.open);
  1565. _proto.open = function open() {
  1566. '[native code]';
  1567. if (checkRequest('xhr', ...arguments)) {
  1568. xhrStopList.add(this);
  1569. return;
  1570. }
  1571. return _open(this, arguments);
  1572. };
  1573. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1574. name => {
  1575. let func = _proto[name];
  1576. _proto[name] = function(...args) {
  1577. return xhrStopList.has(this) ? null : func.apply(this, args);
  1578. };
  1579. }
  1580. );
  1581.  
  1582. let _fetch = root.Function.prototype.apply.bind(root.fetch);
  1583. root.fetch = function fetch() {
  1584. '[native code]';
  1585. let url = arguments[0];
  1586. let method = arguments[1] ? arguments[1].method : void 0;
  1587. if (arguments[0] instanceof Request) {
  1588. method = url.method;
  1589. url = url.url;
  1590. }
  1591. if (checkRequest('fetch', method, url))
  1592. return new Promise(() => null);
  1593. return _fetch(root, arguments);
  1594. };
  1595. });
  1596.  
  1597. win.stop = () => {
  1598. console.warn('window.stop() ...y tho?');
  1599. for (let sheet of _document.styleSheets)
  1600. if (sheet.disabled) {
  1601. sheet.disabled = false;
  1602. console.log('Re-enabled:', sheet);
  1603. }
  1604. }
  1605. }, deepWrapAPI
  1606. );
  1607.  
  1608. // === Helper functions ===
  1609.  
  1610. // function to search and remove nodes by content
  1611. // selector - standard CSS selector to define set of nodes to check
  1612. // words - regular expression to check content of the suspicious nodes
  1613. // params - object with multiple extra parameters:
  1614. // .log - display log in the console
  1615. // .hide - set display to none instead of removing from the page
  1616. // .parent - parent node to remove if content is found in the child node
  1617. // .siblings - number of simling nodes to remove (excluding text nodes)
  1618. let scRemove = (node) => node.parentNode.removeChild(node);
  1619. let scHide = function(node) {
  1620. let style = _getAttribute(node, 'style') || '',
  1621. hide = ';display:none!important;';
  1622. if (style.indexOf(hide) < 0)
  1623. _setAttribute(node, 'style', style + hide);
  1624. };
  1625.  
  1626. function scissors (selector, words, scope, params) {
  1627. let logger = (...args) => { if (params.log) console.log(...args) };
  1628. if (!scope.contains(_document.body))
  1629. logger('[s] scope', scope);
  1630. let remFunc = (params.hide ? scHide : scRemove),
  1631. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1632. toRemove = [],
  1633. siblings;
  1634. for (let node of scope.querySelectorAll(selector)) {
  1635. // drill up to a parent node if specified, break if not found
  1636. if (params.parent) {
  1637. let old = node;
  1638. node = node.closest(params.parent);
  1639. if (node === null || node.contains(scope)) {
  1640. logger('[s] went out of scope with', old);
  1641. continue;
  1642. }
  1643. }
  1644. logger('[s] processing', node);
  1645. if (toRemove.includes(node))
  1646. continue;
  1647. if (words.test(node.innerHTML)) {
  1648. // skip node if already marked for removal
  1649. logger('[s] marked for removal');
  1650. toRemove.push(node);
  1651. // add multiple nodes if defined more than one sibling
  1652. siblings = Math.abs(params.siblings) || 0;
  1653. while (siblings) {
  1654. node = node[iterFunc];
  1655. if (!node) break; // can't go any further - exit
  1656. logger('[s] adding sibling node', node);
  1657. toRemove.push(node);
  1658. siblings -= 1;
  1659. }
  1660. }
  1661. }
  1662. let toSkip = [];
  1663. for (let node of toRemove)
  1664. if (!toRemove.every(other => other === node || !node.contains(other)))
  1665. toSkip.push(node);
  1666. if (toRemove.length)
  1667. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1668. for (let node of toRemove) if (!toSkip.includes(node))
  1669. remFunc(node);
  1670. }
  1671.  
  1672. // function to perform multiple checks if ads inserted with a delay
  1673. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1674. // also does 1 extra check when a page completely loads
  1675. // selector and words - passed dow to scissors
  1676. // params - object with multiple extra parameters:
  1677. // .log - display log in the console
  1678. // .root - selector to narrow down scope to scan;
  1679. // .observe - if true then check will be performed continuously;
  1680. // Other parameters passed down to scissors.
  1681. function gardener(selector, words, params) {
  1682. let logger = (...args) => { if (params.log) console.log(...args) };
  1683. params = params || {};
  1684. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1685. let scope;
  1686. let globalScope = [_de];
  1687. let domLoaded = false;
  1688. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1689. let onevent = e => {
  1690. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1691. for (let node of scope)
  1692. scissors(selector, words, node, params);
  1693. };
  1694. let repeater = n => {
  1695. if (!domLoaded && n) {
  1696. setTimeout(repeater, 500, n - 1);
  1697. scope = getScope(params.root);
  1698. if (!scope) // exit if the root element is not present on the page
  1699. return 0;
  1700. onevent({type: 'Repeater'});
  1701. }
  1702. };
  1703. repeater(20);
  1704. _document.addEventListener(
  1705. 'DOMContentLoaded', (e) => {
  1706. domLoaded = true;
  1707. // narrow down scope to a specific element
  1708. scope = getScope(params.root);
  1709. if (!scope) // exit if the root element is not present on the page
  1710. return 0;
  1711. logger('[g] scope', scope);
  1712. // add observe mode if required
  1713. if (params.observe) {
  1714. let params = { childList:true, subtree: true };
  1715. let observer = new MutationObserver(
  1716. function(ms) {
  1717. for (let m of ms)
  1718. if (m.addedNodes.length)
  1719. onevent(m);
  1720. }
  1721. );
  1722. for (let node of scope)
  1723. observer.observe(node, params);
  1724. logger('[g] observer enabled');
  1725. }
  1726. onevent(e);
  1727. }, false);
  1728. // wait for a full page load to do one extra cut
  1729. win.addEventListener('load', onevent, false);
  1730. }
  1731.  
  1732. // wrap popular methods to open a new tab to catch specific behaviours
  1733. function createWindowOpenWrapper(openFunc) {
  1734. let _createElement = _Document.prototype.createElement,
  1735. _appendChild = _Element.prototype.appendChild,
  1736. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1737.  
  1738. let nt = new nullTools();
  1739. fakeNative(openFunc);
  1740.  
  1741. let parser = _createElement.call(_document, 'a');
  1742. let openWhitelist = (url, parent) => {
  1743. parser.href = url;
  1744. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1745. parent.hostname === 'radikal.ru' && url === void 0;
  1746. };
  1747.  
  1748. let redefineOpen = (root) => {
  1749. if ('open' in root) {
  1750. let _open = root.open.bind(root);
  1751. nt.define(root, 'open', (...args) => {
  1752. if (openWhitelist(args[0], location)) {
  1753. console.log('Whitelisted popup:', ...args);
  1754. return _open(...args);
  1755. }
  1756. return openFunc(...args);
  1757. });
  1758. }
  1759. };
  1760. redefineOpen(win);
  1761.  
  1762. function createElement() {
  1763. '[native code]';
  1764. let el = _createElement.apply(this, arguments);
  1765. // redefine window.open in first-party frames
  1766. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1767. el.addEventListener('load', (e) => {
  1768. try {
  1769. redefineOpen(e.target.contentWindow);
  1770. } catch(ignore) {}
  1771. }, false);
  1772. return el;
  1773. }
  1774. fakeNative(createElement);
  1775.  
  1776. let redefineCreateElement = (obj) => {
  1777. for (let root of [obj.document, _Document.prototype]) if ('createElement' in root)
  1778. nt.define(root, 'createElement', createElement);
  1779. };
  1780. redefineCreateElement(win);
  1781.  
  1782. // wrap window.open in newly added first-party frames
  1783. _Element.prototype.appendChild = function appendChild() {
  1784. '[native code]';
  1785. let el = _appendChild.apply(this, arguments);
  1786. if (el instanceof HTMLIFrameElement)
  1787. try {
  1788. redefineOpen(el.contentWindow);
  1789. redefineCreateElement(el.contentWindow);
  1790. } catch(ignore) {}
  1791. return el;
  1792. };
  1793. fakeNative(_Element.prototype.appendChild);
  1794. }
  1795.  
  1796. // Function to catch and block various methods to open a new window with 3rd-party content.
  1797. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1798. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1799. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1800. // node or simply a link with piece of javascript code in the HREF attribute.
  1801. function preventPopups() {
  1802. // call sandbox-me if in iframe and not whitelisted
  1803. if (inIFrame) {
  1804. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1805. return;
  1806. }
  1807.  
  1808. scriptLander(() => {
  1809. let nt = new nullTools({log:true});
  1810. let open = (...args) => {
  1811. '[native code]';
  1812. console.warn('Site attempted to open a new window', ...args);
  1813. return {
  1814. document: nt.proxy({
  1815. write: nt.func({}, 'write'),
  1816. writeln: nt.func({}, 'writeln')
  1817. }),
  1818. location: nt.proxy({})
  1819. };
  1820. };
  1821.  
  1822. createWindowOpenWrapper(open);
  1823.  
  1824. console.log('Popup prevention enabled.');
  1825. }, nullTools, createWindowOpenWrapper);
  1826. }
  1827.  
  1828. // Helper function to close background tab if site opens itself in a new tab and then
  1829. // loads a 3rd-party page in the background one (thus performing background redirect).
  1830. function preventPopunders() {
  1831. // create "close_me" event to call high-level window.close()
  1832. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1833. let callClose = () => {
  1834. console.log('close call');
  1835. window.close();
  1836. };
  1837. window.addEventListener(eventName, callClose, true);
  1838.  
  1839. scriptLander(() => {
  1840. // get host of a provided URL with help of an anchor object
  1841. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1842. let parseURL = _document.createElement('A');
  1843. let getHost = url => {
  1844. parseURL.href = url;
  1845. return parseURL.hostname
  1846. };
  1847. // site went to a new tab and attempts to unload
  1848. // call for high-level close through event
  1849. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1850. // check is URL local or goes to different site
  1851. let isLocal = (url) => {
  1852. if (url === location.pathname || url === location.href)
  1853. return true; // URL points to current pathname or full address
  1854. let host = getHost(url);
  1855. let site = location.hostname;
  1856. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1857. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1858. };
  1859.  
  1860. let _open = window.open.bind(window);
  1861. let open = (...args) => {
  1862. '[native code]';
  1863. let url = args[0];
  1864. if (url && isLocal(url))
  1865. window.addEventListener('beforeunload', closeWindow, true);
  1866. return _open(...args);
  1867. };
  1868.  
  1869. createWindowOpenWrapper(open);
  1870.  
  1871. console.log("Background redirect prevention enabled.");
  1872. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1873. }
  1874.  
  1875. // Mix between check for popups and popunders
  1876. // Significantly more agressive than both and can't be used as universal solution
  1877. function preventPopMix() {
  1878. if (inIFrame) {
  1879. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1880. return;
  1881. }
  1882.  
  1883. // create "close_me" event to call high-level window.close()
  1884. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1885. let callClose = () => {
  1886. console.log('close call');
  1887. window.close();
  1888. };
  1889. window.addEventListener(eventName, callClose, true);
  1890.  
  1891. scriptLander(() => {
  1892. let _open = window.open,
  1893. parseURL = _document.createElement('A');
  1894. // get host of a provided URL with help of an anchor object
  1895. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1896. let getHost = (url) => {
  1897. parseURL.href = url;
  1898. return parseURL.host;
  1899. };
  1900. // site went to a new tab and attempts to unload
  1901. // call for high-level close through event
  1902. let closeWindow = () => {
  1903. _open(window.location,'_self');
  1904. window.dispatchEvent(new CustomEvent(eventName, {}));
  1905. };
  1906. // check is URL local or goes to different site
  1907. function isLocal(url) {
  1908. let loc = window.location;
  1909. if (url === loc.pathname || url === loc.href)
  1910. return true; // URL points to current pathname or full address
  1911. let host = getHost(url),
  1912. site = loc.host;
  1913. if (host === '')
  1914. return false; // URLs with unusual protocol may have empty 'host'
  1915. if (host.length > site.length)
  1916. [site, host] = [host, site];
  1917. return site.includes(host, site.length - host.length);
  1918. }
  1919.  
  1920. // add check for redirect for 5 seconds, then disable it
  1921. function checkRedirect() {
  1922. window.addEventListener('beforeunload', closeWindow, true);
  1923. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1924. }
  1925.  
  1926. function open(url, name) {
  1927. '[native code]';
  1928. if (url && isLocal(url) && (!name || name === '_blank')) {
  1929. console.warn('Suspicious local new window', arguments);
  1930. checkRedirect();
  1931. return _open.apply(this, arguments);
  1932. }
  1933. console.warn('Blocked attempt to open a new window', arguments);
  1934. return {
  1935. document: {
  1936. write: () => {},
  1937. writeln: () => {}
  1938. }
  1939. };
  1940. }
  1941.  
  1942. function clickHandler(e) {
  1943. let link = e.target,
  1944. url = link.href||'';
  1945. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1946. console.log('Link', link, 'were created dinamically, but looks fine.');
  1947. return true;
  1948. }
  1949. if (isLocal(url) && link.target === '_blank') {
  1950. console.log('Suspicious local link', link);
  1951. checkRedirect();
  1952. return;
  1953. }
  1954. console.log('Blocked suspicious click on a link', link);
  1955. e.stopPropagation();
  1956. e.preventDefault();
  1957. }
  1958.  
  1959. createWindowOpenWrapper(open, clickHandler);
  1960.  
  1961. console.log("Mixed popups prevention enabled.");
  1962. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  1963. }
  1964. // External listener for case when site known to open popups were loaded in iframe
  1965. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1966. // Some sites replace frame's window.location with data-url to run in clean context
  1967. if (!inIFrame) window.addEventListener(
  1968. 'message', function(e) {
  1969. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1970. return;
  1971. let src = e.data.href;
  1972. for (let frame of _document.querySelectorAll('iframe'))
  1973. if (frame.contentWindow === e.source) {
  1974. if (frame.hasAttribute('sandbox')) {
  1975. if (!frame.sandbox.contains('allow-popups'))
  1976. return; // exit frame since it's already sandboxed and popups are blocked
  1977. // remove allow-popups if frame already sandboxed
  1978. frame.sandbox.remove('allow-popups');
  1979. } else
  1980. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1981. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1982. // but to apply content must be reloaded and this script will re-apply it in the result
  1983. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1984. console.log('Disallowed popups from iframe', frame);
  1985.  
  1986. // reload frame content to apply restrictions
  1987. if (!src) {
  1988. src = frame.src;
  1989. console.log('Unable to get current iframe location, reloading from src', src);
  1990. } else
  1991. console.log('Reloading iframe with URL', src);
  1992. frame.src = 'about:blank';
  1993. frame.src = src;
  1994. }
  1995. }, false
  1996. );
  1997.  
  1998. function selectiveEval(extra) {
  1999. scriptLander(() => {
  2000. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2001. if (!_eval_def || !_eval_def.value) {
  2002. console.log('Unable to wrap window.eval.', _eval_def);
  2003. return;
  2004. }
  2005. let genericPatterns = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2006. let _eval_val = _eval_def.value;
  2007. _eval_def.value = function(...args) {
  2008. if (genericPatterns.test(args[0]) || extra && extra.test(args[0])) {
  2009. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2010. return null;
  2011. }
  2012. return _eval_val.apply(this, args);
  2013. };
  2014. Object.defineProperty(win, 'eval', _eval_def);
  2015. }, `let extra = ${extra}`);
  2016. }
  2017.  
  2018. // hides cookies by pattern and attempts to remove them if they already set
  2019. // also prevents setting new versions of such cookies
  2020. function selectiveCookies(scPattern, scPaths = []) {
  2021. scriptLander(() => {
  2022. let ga = '_g(at?|id)|__utm[a-z]'; // Google Analytics Cookies
  2023. scPattern = new RegExp(`(^|;\\s?)(${scPattern}|${ga})($|=)`);
  2024. if (isFirefox && scPaths.length)
  2025. scPaths.forEach((path, id) => scPaths[id] = `${path}/`);
  2026. scPaths.push('/');
  2027. let _doc_proto = ('cookie' in _Document.prototype) ? _Document.prototype : Object.getPrototypeOf(_document);
  2028. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2029. if (_cookie) {
  2030. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2031. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2032. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2033. let expireAge = '-99999999';
  2034. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2035. let expireAttempted = {};
  2036. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2037. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2038. let expire = (cookie, that) => {
  2039. let domain = that.location.hostname.split('.'),
  2040. name = cookie.replace(/=.*/,'');
  2041. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2042. while (domain.length > 1) {
  2043. try {
  2044. scPaths.forEach(
  2045. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2046. );
  2047. } catch(e) { console.warn(e); }
  2048. domain.shift();
  2049. }
  2050. expireAttempted[name] = true;
  2051. console.log('Removing existing cookie:', cookie);
  2052. };
  2053. // skip setting unwanted cookies
  2054. _cookie.set = function(value) {
  2055. if (scPattern.test(value)) {
  2056. console.warn('Ignored cookie:', value);
  2057. // try to remove same cookie if it already exists using exact values from the set string
  2058. if (scPattern.test(_get_cookie(this))) {
  2059. let parts = value.split(/;\s?/),
  2060. name = parts[0].replace(/=.*/,''),
  2061. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2062. skip = [name, 'expires', 'Max-Age'];
  2063. for (let part of parts)
  2064. if (!skip.includes(part.replace(/=.*/,'')))
  2065. newParts.push(part);
  2066. try {
  2067. _set_cookie(this, newParts.join(';'));
  2068. } catch(e) { console.warn(e); }
  2069. console.log('Removing existing cookie:', name);
  2070. }
  2071. return;
  2072. }
  2073. return _set_cookie(this, value);
  2074. };
  2075. // hide unwanted cookies from site
  2076. _cookie.get = function() {
  2077. let res = _get_cookie(this);
  2078. if (scPattern.test(res)) {
  2079. let stack = [];
  2080. for (let cookie of res.split(/;\s?/))
  2081. if (!scPattern.test(cookie))
  2082. stack.push(cookie);
  2083. else {
  2084. let name = cookie.replace(/=.*/,'');
  2085. if (expireAttempted[name]) {
  2086. console.log('Unable to expire:', cookie);
  2087. expireAttempted[name] = false;
  2088. }
  2089. if (!(name in expireAttempted))
  2090. expire(cookie, this);
  2091. }
  2092. res = stack.join('; ');
  2093. }
  2094. return res;
  2095. };
  2096. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2097. }
  2098. console.log('Active cookies:', document.cookie);
  2099. }, `let scPattern = "${scPattern}", scPaths = ${scPaths}, isFirefox = ${isFirefox};`);
  2100. }
  2101.  
  2102. /*{ // simple toString wrapper, might be useful to prevent detection
  2103. '[native code]';
  2104. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2105. let baseText = Function.prototype.toString.toString();
  2106. let protect = new WeakSet();
  2107. protect.add(_Document.prototype.createElement);
  2108. protect.add(_Node.prototype.appendChild);
  2109. protect.add(_Node.prototype.removeChild);
  2110. win.Function.prototype.toString = function() {
  2111. if (protect.has(this))
  2112. return baseText.replace('toString', this.name);
  2113. return _toString(this);
  2114. };
  2115. protect.add(Function.prototype.toString);
  2116. }*/
  2117.  
  2118. // === Scripts for specific domains ===
  2119.  
  2120. let scripts = {};
  2121. // prevent popups and redirects block
  2122. // Popups
  2123. scripts.preventPopups = {
  2124. other: [
  2125. 'biqle.ru',
  2126. 'chaturbate.com',
  2127. 'dfiles.ru',
  2128. 'eporner.eu',
  2129. 'hentaiz.org',
  2130. 'mirrorcreator.com',
  2131. 'online-multy.ru',
  2132. 'radikal.ru', 'rumedia.ws',
  2133. 'tapehub.tech', 'thepiratebay.org',
  2134. 'unionpeer.com',
  2135. 'zippyshare.com'
  2136. ],
  2137. now: preventPopups
  2138. };
  2139. // Popunders (background redirect)
  2140. scripts.preventPopunders = {
  2141. other: [
  2142. 'lostfilm-online.ru',
  2143. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2144. 'perfectgirls.net'
  2145. ],
  2146. now: preventPopunders
  2147. };
  2148. // PopMix (both types of popups encountered on site)
  2149. scripts['openload.co'] = {
  2150. other: ['oload.tv', 'oload.info'],
  2151. now: () => {
  2152. let nt = new nullTools();
  2153. nt.define(win, 'CNight', win.CoinHive);
  2154. if (location.pathname.startsWith('/embed/')) {
  2155. nt.define(win, 'BetterJsPop', {
  2156. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2157. config: ((o) => console.warn('BetterJsPop.config', o)),
  2158. Browser: { isChrome: true }
  2159. });
  2160. nt.define(win, 'isSandboxed', nt.func(null));
  2161. nt.define(win, 'adblock', false);
  2162. nt.define(win, 'adblock2', false);
  2163. } else preventPopMix();
  2164. }
  2165. };
  2166. scripts['turbobit.net'] = preventPopMix;
  2167.  
  2168. scripts['tapochek.net'] = () => {
  2169. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2170. let _appendChild = Object.getOwnPropertyDescriptor(_Node.prototype, 'appendChild');
  2171. let _appendChild_value = _appendChild.value;
  2172. _appendChild.value = function appendChild(node) {
  2173. if (this === _document.body)
  2174. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2175. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2176. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2177. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2178. throw '...eenope!';
  2179. return _appendChild_value.apply(this, arguments);
  2180. };
  2181. Object.defineProperty(_Node.prototype, 'appendChild', _appendChild);
  2182.  
  2183. // disable window focus tricks and changing location
  2184. let focusHandlerName = /\WfocusAchieved\(/
  2185. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2186. let _setInterval = win.setInterval;
  2187. win.setInterval = (...args) => {
  2188. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2189. console.log('skip setInterval for', ...args);
  2190. return -1;
  2191. }
  2192. return _setInterval(...args);
  2193. };
  2194. let _addEventListener = win.addEventListener;
  2195. win.addEventListener = function(...args) {
  2196. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2197. console.log('skip addEventListener for', ...args);
  2198. return void 0;
  2199. }
  2200. return _addEventListener.apply(this, args);
  2201. };
  2202.  
  2203. // generic popup prevention
  2204. preventPopups();
  2205. };
  2206.  
  2207. scripts['rustorka.com'] = {
  2208. other: ['rustorka.club', 'rustorka.lib', 'rustorka.net'],
  2209. now: () => {
  2210. selectiveEval(/antiadblock/);
  2211. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2212. scriptLander(() => {
  2213. // wrap window.open to catch a popup if it triggers
  2214. win.open = (...args) => {
  2215. console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2216. location.replace(location.href);
  2217. return null;
  2218. };
  2219. window.addEventListener('DOMContentLoaded', () => {
  2220. let link = void 0;
  2221. _document.body.addEventListener('mousedown', e => {
  2222. link = e.target.closest('a, select, #fancybox-title-wrap');
  2223. }, false);
  2224. let _open = window.open.bind(window);
  2225. let _getAttribute = Function.prototype.call.bind(_Element.prototype.getAttribute);
  2226. win.open = (...args) => {
  2227. let url = args[0];
  2228. if (link instanceof HTMLAnchorElement) {
  2229. // third-party post links
  2230. let href = _getAttribute(link, 'href');
  2231. if (link.classList.contains('postLink') &&
  2232. !link.matches(`a[href*="${location.hostname}"]`) &&
  2233. (href === url || link.href === url))
  2234. return _open(...args);
  2235. // onclick # links
  2236. if (href === '#' && /window\.open/.test(_getAttribute(link, 'onclick')))
  2237. return _open(...args);
  2238. // force local links to load in the current window
  2239. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2240. location.assign(href);
  2241. }
  2242. // list of image hostings under upload picture button (new comment)
  2243. if (link instanceof HTMLSelectElement &&
  2244. !url.includes(location.hostname) &&
  2245. link.value === url)
  2246. return _open(...args);
  2247. // open screenshot in a new window
  2248. if (link instanceof HTMLSpanElement &&
  2249. link.id === 'fancybox-title-wrap')
  2250. return _open(...args);
  2251. // looks like tabunder
  2252. if (link === null && url === location.href)
  2253. location.replace(url); // reload current page
  2254. // other cases
  2255. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2256. return {};
  2257. };
  2258. }, true);
  2259. }, nullTools)
  2260. }
  2261. };
  2262.  
  2263. // = other ======================================================================================
  2264. scripts['1tv.ru'] = {
  2265. other: ['mediavitrina.ru'],
  2266. now: () => scriptLander(() => {
  2267. let nt = new nullTools();
  2268. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2269. let disablePlugins = {
  2270. 'antiblock': false,
  2271. 'stat1tv': false
  2272. };
  2273. let _EUMPConfig = void 0;
  2274. let _EUMPConfig_set = x => {
  2275. if (x.plugins) {
  2276. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2277. console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2278. }
  2279. _EUMPConfig = x;
  2280. };
  2281. if ('EUMPConfig' in win)
  2282. _EUMPConfig_set(win.EUMPConfig);
  2283. Object.defineProperty(win, 'EUMPConfig', {
  2284. enumerable: true,
  2285. get: () => _EUMPConfig,
  2286. set: _EUMPConfig_set
  2287. });
  2288. }, nullTools)
  2289. };
  2290.  
  2291. scripts['2picsun.ru'] = {
  2292. other: [
  2293. 'pics2sun.ru', '3pics-img.ru'
  2294. ],
  2295. now: () => {
  2296. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2297. }
  2298. };
  2299.  
  2300. scripts['4pda.ru'] = {
  2301. now: () => {
  2302. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2303. let isForum = location.pathname.startsWith('/forum/'),
  2304. remove = node => (node && node.parentNode.removeChild(node)),
  2305. hide = node => (node && (node.style.display = 'none'));
  2306.  
  2307. // save links to non-overridden functions to use later
  2308. let protectedElems;
  2309. // protect/hide changed attributes in case site attempt to restore them
  2310. function styleProtector(eventMode) {
  2311. let _toLowerCase = String.prototype.toLowerCase,
  2312. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2313. protectedElems = new WeakMap();
  2314. function protoOverride(element, functionName, isStyleCheck, returnIfProtected) {
  2315. let originalFunction = element.prototype[functionName];
  2316. element.prototype[functionName] = function wrapper() {
  2317. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2318. return returnIfProtected(this, arguments);
  2319. return originalFunction.apply(this, arguments);
  2320. };
  2321. }
  2322. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2323. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2324. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2325. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2326. if (!eventMode)
  2327. return protectedElems;
  2328. let e = _document.createEvent('Event');
  2329. e.initEvent('protoOverride', false, false);
  2330. window.protectedElems = protectedElems;
  2331. window.dispatchEvent(e);
  2332. }
  2333. if (!isFirefox)
  2334. protectedElems = styleProtector(false);
  2335. else {
  2336. let script = _document.createElement('script');
  2337. script.textContent = `(${styleProtector.toString()})(true);`;
  2338. window.addEventListener(
  2339. 'protoOverride', function protoOverrideCallback() {
  2340. if (win.protectedElems) {
  2341. protectedElems = win.protectedElems;
  2342. delete win.protectedElems;
  2343. }
  2344. _document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2345. }, true
  2346. );
  2347. _appendChild(script);
  2348. _removeChild(script);
  2349. }
  2350.  
  2351. // clean a page
  2352. window.addEventListener(
  2353. 'DOMContentLoaded', function() {
  2354. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2355. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2356.  
  2357. HeaderAds: {
  2358. // hide ads above HEADER
  2359. let header = _document.querySelector('.drop-search');
  2360. if (!header) {
  2361. console.warn('Unable to locate header element');
  2362. break HeaderAds;
  2363. }
  2364. header = header.parentNode.parentNode;
  2365. for (let itm of header.parentNode.children)
  2366. if (itm !== header)
  2367. hide(itm);
  2368. else break;
  2369. }
  2370.  
  2371. if (isForum) {
  2372. let itm = _document.querySelector('#logostrip');
  2373. if (itm)
  2374. remove(itm.parentNode.nextSibling);
  2375. // clear background in the download frame
  2376. if (location.pathname.startsWith('/forum/dl/')) {
  2377. let setBackground = node => _setAttribute(
  2378. node,
  2379. 'style', (_getAttribute(node, 'style') || '') +
  2380. ';background-color:#4ebaf6!important'
  2381. );
  2382. setBackground(_document.body);
  2383. for (let itm of _document.querySelectorAll('body > div'))
  2384. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2385. remove(itm);
  2386. else
  2387. setBackground(itm);
  2388. }
  2389. // exist from DOMContentLoaded since the rest is not for forum
  2390. return;
  2391. }
  2392.  
  2393. FixNavMenu: {
  2394. // restore DevDB link in the navigation
  2395. let itm = _document.querySelector('#nav li a[href$="/devdb/"]')
  2396. if (!itm) {
  2397. console.warn('Unable to locate navigation menu');
  2398. break FixNavMenu;
  2399. }
  2400. itm.closest('li').style.display = 'block';
  2401. // hide ad link from the navigation
  2402. hide(_document.querySelector('#nav li a[data-dotrack]'));
  2403. }
  2404. SidebarAds: {
  2405. // remove ads from sidebar
  2406. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child');
  2407. if (!aside.length) {
  2408. console.warn('Unable to locate sidebar');
  2409. break SidebarAds;
  2410. }
  2411. let post;
  2412. for (let side of aside) {
  2413. console.log('Processing potential sidebar:', side);
  2414. for (let itm of Array.from(side.children)) {
  2415. post = itm.classList.contains('post');
  2416. if (itm.querySelector('iframe') && !post)
  2417. remove(itm);
  2418. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2419. hide(itm);
  2420. }
  2421. }
  2422. }
  2423.  
  2424. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2425.  
  2426. let extra = 'background-image:none!important;background-color:transparent!important',
  2427. fakeStyles = new WeakMap(),
  2428. styleProxy = {
  2429. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2430. set: function(target, prop, value) {
  2431. let fakeStyle = fakeStyles.get(target);
  2432. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2433. return true;
  2434. }
  2435. };
  2436. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2437. if (!(itm.offsetWidth > 0.95 * width() &&
  2438. itm.offsetHeight > 0.85 * height()))
  2439. continue;
  2440. if (itm.tagName !== 'A') {
  2441. fakeStyles.set(itm.style, {
  2442. 'backgroundImage': itm.style.backgroundImage,
  2443. 'backgroundColor': itm.style.backgroundColor
  2444. });
  2445.  
  2446. try {
  2447. Object.defineProperty(itm, 'style', {
  2448. value: new Proxy(itm.style, styleProxy),
  2449. enumerable: true
  2450. });
  2451. } catch (e) {
  2452. console.log('Unable to protect style property.', e);
  2453. }
  2454.  
  2455. if (protectedElems)
  2456. protectedElems.set(itm, _getAttribute(itm, 'style'));
  2457.  
  2458. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2459. }
  2460. if (itm.tagName === 'A') {
  2461. if (protectedElems)
  2462. protectedElems.set(itm, _getAttribute(itm, 'style'));
  2463. _setAttribute(itm, 'style', 'display:none!important');
  2464. }
  2465. }
  2466. }
  2467. );
  2468. }
  2469. };
  2470.  
  2471. scripts['adhands.ru'] = () => scriptLander(() => {
  2472. let nt = new nullTools();
  2473. try {
  2474. let _adv;
  2475. Object.defineProperty(win, 'adv', {
  2476. get: () => _adv,
  2477. set: (v) => {
  2478. console.log('Blocked advert on adhands.ru.');
  2479. nt.define(v, 'advert', '');
  2480. _adv = v;
  2481. }
  2482. });
  2483. } catch (ignore) {
  2484. if (!win.adv)
  2485. console.log('Unable to locate advert on adhands.ru.');
  2486. else {
  2487. console.log('Blocked advert on adhands.ru.');
  2488. nt.define(win.adv, 'advert', '');
  2489. }
  2490. }
  2491. }, nullTools);
  2492.  
  2493. scripts['all-episodes.tv'] = () => {
  2494. let nt = new nullTools();
  2495. nt.define(win, 'perX1', 2);
  2496. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2497. };
  2498.  
  2499. scripts['allhentai.ru'] = () => {
  2500. selectiveEval();
  2501. preventPopups();
  2502. scriptLander(() => {
  2503. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2504. if (!_onerror)
  2505. return;
  2506. _onerror.set = (...args) => console.log(args[0].toString());
  2507. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2508. });
  2509. };
  2510.  
  2511. scripts['allmovie.pro'] = {
  2512. other: ['rufilmtv.org'],
  2513. dom: function() {
  2514. // pretend to be Android to make site use different played for ads
  2515. if (isSafari)
  2516. return;
  2517. Object.defineProperty(navigator, 'userAgent', {
  2518. get: function(){
  2519. 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';
  2520. },
  2521. enumerable: true
  2522. });
  2523. }
  2524. };
  2525.  
  2526. scripts['anidub-online.ru'] = {
  2527. other: ['anime.anidub.com', 'online.anidub.com'],
  2528. dom: function() {
  2529. if (win.ogonekstart1)
  2530. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2531. },
  2532. now: () => createStyle([
  2533. '.background {background: none!important;}',
  2534. '.background > script + div,'+
  2535. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2536. '{display:none!important}'
  2537. ])
  2538. };
  2539.  
  2540. scripts['avito.ru'] = () => selectiveCookies('abp|bltsr|cmtchd|crookie|is_adblock');
  2541.  
  2542. scripts['drive2.ru'] = () => {
  2543. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2544. scriptLander(() => {
  2545. let _d2 = void 0;
  2546. Object.defineProperty(win, 'd2', {
  2547. get: () => _d2,
  2548. set: o => {
  2549. if (o === _d2)
  2550. return true;
  2551. _d2 = new Proxy(o, {
  2552. set: (tgt, prop, val) => {
  2553. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2554. val = () => null;
  2555. tgt[prop] = val;
  2556. return true;
  2557. }
  2558. });
  2559. }
  2560. });
  2561. });
  2562. };
  2563.  
  2564. scripts['fastpic.ru'] = () => {
  2565. let nt = new nullTools();
  2566. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2567. nt.define(win, `_0x${'4955'}`, []);
  2568. };
  2569.  
  2570. scripts['fishki.net'] = () => {
  2571. scriptLander(() => {
  2572. let nt = new nullTools();
  2573. let fishki = {};
  2574. nt.define(fishki, 'adv', nt.proxy({
  2575. afterAdblockCheck: nt.func(null),
  2576. refreshFloat: nt.func(null)
  2577. }));
  2578. nt.define(fishki, 'is_adblock', false);
  2579. nt.define(win, 'fishki', fishki);
  2580. }, nullTools);
  2581. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2582. };
  2583.  
  2584. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2585.  
  2586. scripts['hdgo.cc'] = {
  2587. other: ['46.30.43.38', 'couber.be'],
  2588. now: () => (new MutationObserver(
  2589. (ms) => {
  2590. let m, node;
  2591. for (m of ms) for (node of m.addedNodes)
  2592. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2593. node.removeAttribute('onerror');
  2594. }
  2595. )).observe(_document.documentElement, { childList:true, subtree: true })
  2596. };
  2597.  
  2598. scripts['gismeteo.ru'] = {
  2599. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2600. now: () => {
  2601. selectiveCookies('ab_[^=]*|bltsr|redirect|_gab');
  2602. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2603. }
  2604. };
  2605.  
  2606. scripts['hdrezka.ag'] = () => {
  2607. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2608. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2609. };
  2610.  
  2611. scripts['hqq.tv'] = () => scriptLander(() => {
  2612. // disable anti-debugging in hqq.tv player
  2613. 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);
  2614. deepWrapAPI(root => {
  2615. // skip obfuscated stuff and a few other calls
  2616. let _setInterval = root.setInterval,
  2617. _setTimeout = root.setTimeout,
  2618. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2619. root.setInterval = (...args) => {
  2620. let fun = args[0];
  2621. if (fun instanceof Function) {
  2622. let text = _toString(fun),
  2623. skip = text.includes('check();') || isObfuscated(text);
  2624. console.warn('setInterval', text, 'skip', skip);
  2625. if (skip) return -1;
  2626. }
  2627. return _setInterval.apply(this, args);
  2628. };
  2629. let wrappedST = new WeakSet();
  2630. root.setTimeout = (...args) => {
  2631. let fun = args[0];
  2632. if (fun instanceof Function) {
  2633. let text = _toString(fun),
  2634. skip = fun.name === 'check' || isObfuscated(text);
  2635. if (!wrappedST.has(fun)) {
  2636. console.warn('setTimeout', text, 'skip', skip);
  2637. wrappedST.add(fun);
  2638. }
  2639. if (skip) return;
  2640. }
  2641. return _setTimeout.apply(this, args);
  2642. };
  2643. // skip 'debugger' call
  2644. let _eval = root.eval;
  2645. root.eval = text => {
  2646. if (typeof text === 'string' && text.includes('debugger;')) {
  2647. console.warn('skip eval', text);
  2648. return;
  2649. }
  2650. _eval(text);
  2651. };
  2652. // Prevent RegExpt + toString trick
  2653. let _proto = void 0;
  2654. try {
  2655. _proto = root.RegExp.prototype;
  2656. } catch(ignore) {
  2657. return;
  2658. }
  2659. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  2660. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  2661. Object.defineProperty(_proto, 'toString', {
  2662. enumerable: _RE_tS.enumerable,
  2663. configurable: _RE_tS.configurable,
  2664. get: () => _RE_tSV,
  2665. set: val => console.warn('Attempt to change toString for', this, 'with', _toString(val))
  2666. });
  2667. });
  2668. }, deepWrapAPI);
  2669.  
  2670. scripts['hideip.me'] = {
  2671. now: () => scriptLander(() => {
  2672. let _innerHTML = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML');
  2673. let _set_innerHTML = _innerHTML.set;
  2674. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2675. let _get_innerText = _innerText.get;
  2676. let div = _document.createElement('div');
  2677. _innerHTML.set = function(...args) {
  2678. _set_innerHTML.call(div, args[0].replace('i','a'));
  2679. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2680. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2681. console.log('Anti-Adblock killed.');
  2682. return true;
  2683. }
  2684. _set_innerHTML.apply(this, args);
  2685. };
  2686. Object.defineProperty(_Element.prototype, 'innerHTML', _innerHTML);
  2687. Object.defineProperty(win, 'adblock', {
  2688. get: () => false,
  2689. set: () => null,
  2690. enumerable: true
  2691. });
  2692. let _$ = {};
  2693. let _$_map = new WeakMap();
  2694. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2695. let _val_gOPD = _gOPD.value;
  2696. _gOPD.value = function(...args) {
  2697. let _res = _val_gOPD.apply(this, args);
  2698. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2699. delete _res.get;
  2700. delete _res.set;
  2701. _res.value = win[args[1]];
  2702. }
  2703. return _res;
  2704. };
  2705. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2706. let getJQWrap = (n) => {
  2707. let name = n;
  2708. return {
  2709. enumerable: true,
  2710. get: () => _$[name],
  2711. set: x => {
  2712. if (_$_map.has(x)) {
  2713. _$[name] = _$_map.get(x);
  2714. return true;
  2715. }
  2716. if (x === _$.$ || x === _$.jQuery) {
  2717. _$[name] = x;
  2718. return true;
  2719. }
  2720. _$[name] = new Proxy(x, {
  2721. apply: (t, o, args) => {
  2722. let _res = t.apply(o, args);
  2723. if (_$_map.has(_res.is))
  2724. _res.is = _$_map.get(_res.is);
  2725. else {
  2726. let _is = _res.is;
  2727. _res.is = function(...args) {
  2728. if (args[0] === ':hidden')
  2729. return false;
  2730. return _is.apply(this, args);
  2731. };
  2732. _$_map.set(_is, _res.is);
  2733. }
  2734. return _res;
  2735. }
  2736. });
  2737. _$_map.set(x, _$[name]);
  2738. return true;
  2739. }
  2740. };
  2741. };
  2742. Object.defineProperty(win, '$', getJQWrap('$'));
  2743. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2744. let _dP = Object.defineProperty;
  2745. Object.defineProperty = function(...args) {
  2746. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2747. return void 0;
  2748. return _dP.apply(this, args);
  2749. };
  2750. })
  2751. };
  2752.  
  2753. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2754. let nt = new nullTools();
  2755. /*jslint evil: true */ // yes, evil, I know
  2756. let _write = _document.write.bind(_document);
  2757. /*jslint evil: false */
  2758. nt.define(_document, 'write', t => {
  2759. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2760. if (id && id[1])
  2761. return _write(`<div id="${id[1]}"></div>${t}`);
  2762. return _write('');
  2763. });
  2764. });
  2765.  
  2766. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  2767.  
  2768. scripts['ivi.ru'] = () => {
  2769. let _xhr_open = win.XMLHttpRequest.prototype.open;
  2770. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  2771. if (typeof url === 'string')
  2772. if (url.endsWith('/track'))
  2773. return;
  2774. return _xhr_open.call(this, method, url, ...args);
  2775. };
  2776. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  2777. let _responseText_get = _responseText.get;
  2778. _responseText.get = function() {
  2779. if (this.__responseText__)
  2780. return this.__responseText__;
  2781. let res = _responseText_get.apply(this, arguments);
  2782. let o;
  2783. try {
  2784. if (res)
  2785. o = JSON.parse(res);
  2786. } catch(ignore) {};
  2787. let changed = false;
  2788. if (o && o.result) {
  2789. if (o.result instanceof Array &&
  2790. 'adv_network_logo_url' in o.result[0]) {
  2791. o.result = [];
  2792. changed = true;
  2793. }
  2794. if (o.result.show_adv) {
  2795. o.result.show_adv = false;
  2796. changed = true;
  2797. }
  2798. }
  2799. if (changed) {
  2800. console.log('changed response >>', o);
  2801. res = JSON.stringify(o);
  2802. }
  2803. this.__responseText__ = res;
  2804. return res;
  2805. };
  2806. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  2807. };
  2808.  
  2809. scripts['kinopoisk.ru'] = () => {
  2810. selectiveCookies('bltsr|cmtchd|crookie|kpunk');
  2811. // set no-branding body style and adjust other blocks on the page
  2812. createStyle([
  2813. 'body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }',
  2814. '#top { height: 150px !important }',
  2815. '#top_superscreen { display: none !important }',
  2816. '#top_3banners { display: block !important }'
  2817. ]);
  2818. // catch branding and other things
  2819. let _KP = void 0;
  2820. Object.defineProperty(win, 'KP', {
  2821. get: () => _KP,
  2822. set: val => {
  2823. if (_KP === val)
  2824. return true;
  2825. _KP = new Proxy(val, {
  2826. set: (kp, name, val) => {
  2827. if (name === 'branding')
  2828. return true;
  2829. if (name === 'config')
  2830. val = new Proxy(val, {
  2831. set: (cfg, name, val) => {
  2832. if (name === 'anContextUrl')
  2833. return true;
  2834. if (name === 'adfoxEnabled' || name === 'hasBranding')
  2835. val = false;
  2836. if (name === 'adfoxVideoAdUrls')
  2837. val = {flash:{}, html:{}};
  2838. cfg[name] = val;
  2839. return true;
  2840. }
  2841. });
  2842. kp[name] = val;
  2843. return true;
  2844. }
  2845. });
  2846. console.log('KP =', val);
  2847. }
  2848. });
  2849. };
  2850.  
  2851. scripts['kinozal-tv.appspot.com'] = {
  2852. other: ['a-dot-kinozal-tv.appspot.com'],
  2853. now: () => {
  2854. // They check if 'startsWith' in String.prototype
  2855. // and skip parts of ABP detector if it's not there
  2856. delete String.prototype.startsWith;
  2857. }
  2858. };
  2859.  
  2860. scripts['korrespondent.net'] = {
  2861. now: () => scriptLander(() => {
  2862. let nt = new nullTools();
  2863. nt.define(win, 'holder', function(id) {
  2864. let div = _document.getElementById(id);
  2865. if (!div)
  2866. return;
  2867. if (div.parentNode.classList.contains('col__sidebar')) {
  2868. div.parentNode.appendChild(div);
  2869. div.style.height = '300px';
  2870. }
  2871. });
  2872. }, nullTools),
  2873. dom: () => {
  2874. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  2875. frame.parentNode.style.width = '1px';
  2876. }
  2877. };
  2878.  
  2879. scripts['mail.ru'] = {
  2880. other: ['ok.ru'],
  2881. now: () => scriptLander(() => {
  2882. let nt = new nullTools();
  2883. // Trick to prevent mail.ru from removing 3rd-party styles
  2884. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2885. // Disable some of their counters
  2886. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2887. if (location.hostname === 'e.mail.ru')
  2888. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2889. else
  2890. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2891.  
  2892. {
  2893. let missingCheck = {
  2894. get: (obj, name) => {
  2895. if (!(name in obj))
  2896. console.warn(obj, 'missing:', name);
  2897. return obj[name];
  2898. }
  2899. };
  2900. let redefiner = {
  2901. apply: (target, thisArg, args) => {
  2902. let res = void 0;
  2903. let skipLog = (name, ret) => (...args) => (console.log(`Skip ${name}(`, ...args, ')'), ret);
  2904. if (target._name === 'mrg-smokescreen/Welter')
  2905. res = {
  2906. isWelter: () => true,
  2907. wrap: skipLog(`${target._name}.wrap`)
  2908. };
  2909. if (target._name === 'mrg-smokescreen/StyleSheets')
  2910. res = {
  2911. update: skipLog(`${target._name}.update`),
  2912. remove: skipLog(`${target._name}.remove`),
  2913. insert: skipLog(`${target._name}.insert`),
  2914. setup: skipLog(`${target._name}.setup`)
  2915. };
  2916. if (target._name === 'mrg-honeypot/main')
  2917. res = {
  2918. check: skipLog(`${target._name}.check`, false)
  2919. };
  2920. if (target._name.startsWith('advert/rb/slot'))
  2921. res = {
  2922. slot: '0',
  2923. get: () => null,
  2924. getHTML: () => null,
  2925. createBlock: () => null,
  2926. onRedirect: () => null
  2927. };
  2928. if (target._name.startsWith('OK/banners/'))
  2929. res = {
  2930. activate: skipLog(`${target._name}.activate`),
  2931. deactivate: skipLog(`${target._name}.deactivate`)
  2932. };
  2933. if (res)
  2934. res = new Proxy(res, missingCheck);
  2935. else
  2936. res = target.apply(thisArg, args);
  2937. if (target._name === 'advert/RB') {
  2938. res.getSlots = () => [];
  2939. res.load._name = target._name + '.load';
  2940. res.load = new Proxy(res.load, redefiner);
  2941. }
  2942. console.log(target._name, '(',...args,') >>', res);
  2943. return res;
  2944. }
  2945. };
  2946.  
  2947. let wrapAdFuncs = {
  2948. apply: (target, thisArg, args) => {
  2949. let module = args[0];
  2950. if (typeof module === 'string')
  2951. if (module.startsWith('mrg-smoke') ||
  2952. module.startsWith('mrg-context') ||
  2953. module.startsWith('mrg-honeypot') ||
  2954. module.startsWith('advert') ||
  2955. module.startsWith('OK/banner') ||
  2956. module === 'OK/Smokescreen') {
  2957. let fun = args[args.length-1];
  2958. fun._name = module;
  2959. args[args.length-1] = new Proxy(fun, redefiner);
  2960. }// else
  2961. // console.log('Define:', args[0]);
  2962. return target.apply(thisArg, args);
  2963. }
  2964. };
  2965. let wrapDefine = def => {
  2966. if (!def)
  2967. return;
  2968. console.log('define =', def);
  2969. def = new Proxy(def, wrapAdFuncs);
  2970. def._name = 'define';
  2971. return def;
  2972. };
  2973. let _define = wrapDefine(win.define);
  2974. Object.defineProperty(win, 'define', {
  2975. get: () => _define,
  2976. set: x => {
  2977. if (_define === x)
  2978. return true;
  2979. _define = wrapDefine(x);
  2980. return true;
  2981. }
  2982. });
  2983. }
  2984.  
  2985. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2986. let logger = {
  2987. apply: (target, thisArg, args) => {
  2988. let res = target.apply(thisArg, args);
  2989. console.log(`${target._name}(`, ...args, `) >>`, res);
  2990. return res;
  2991. }
  2992. };
  2993.  
  2994. function defineLocator(root) {
  2995. let _locator;
  2996.  
  2997. function wrapLocator(locator) {
  2998. if ('setup' in locator) {
  2999. let _setup = locator.setup;
  3000. locator.setup = function(o) {
  3001. if ('enable' in o) {
  3002. o.enable = false;
  3003. console.log('Disable mimic mode.');
  3004. }
  3005. if ('links' in o) {
  3006. o.links = [];
  3007. console.log('Call with empty list of sheets.');
  3008. }
  3009. return _setup.call(this, o);
  3010. };
  3011. locator.insertSheet = () => false;
  3012. locator.wrap = () => false;
  3013. }
  3014. try {
  3015. let names = [];
  3016. for (let name in locator)
  3017. if (locator[name] instanceof Function && name !== 'transform') {
  3018. locator[name]._name = "locator." + name;
  3019. locator[name] = new Proxy(locator[name], logger);
  3020. names.push(name);
  3021. }
  3022. console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3023. } catch(e) {
  3024. console.log(e);
  3025. }
  3026. _locator = locator;
  3027. }
  3028.  
  3029. if ('locator' in root && root.locator) {
  3030. console.log('Found existing "locator" object. :|', root.locator);
  3031. wrapLocator(root.locator);
  3032. }
  3033.  
  3034. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3035. if (!loc_desc || loc_desc.set !== wrapLocator)
  3036. try {
  3037. Object.defineProperty(root, 'locator', {
  3038. set: wrapLocator,
  3039. get: () => _locator
  3040. });
  3041. } catch (err) {
  3042. console.log('Unable to redefine "locator" object!!!', err);
  3043. }
  3044. }
  3045.  
  3046. function defineDetector(mr) {
  3047. let _honeyPot;
  3048. let __ = mr._ || {};
  3049. let check = function() {
  3050. __.STUCK_IN_POT = false;
  3051. return false;
  3052. };
  3053. check._name = 'honeyPot.check';
  3054. let setHoneyPot = o => {
  3055. console.log('[honeyPot]', o);
  3056. o.check = new Proxy(check, logger);
  3057. _honeyPot = o;
  3058. };
  3059. if ('honeyPot' in mr)
  3060. setHoneyPot(mr.honeyPot);
  3061. Object.defineProperty(mr, 'honeyPot', {
  3062. get: () => _honeyPot,
  3063. set: setHoneyPot
  3064. });
  3065.  
  3066. __ = new Proxy(__, {
  3067. get: (t, p) => t[p],
  3068. set: (t, p, v) => {
  3069. console.log(`mr._.${p} =`, v);
  3070. t[p] = v;
  3071. return true;
  3072. }
  3073. });
  3074. mr._ = __;
  3075. }
  3076.  
  3077. function defineAdd(mr) {
  3078. let _add;
  3079. let addWrapper = {
  3080. apply: (tgt, that, args) => {
  3081. let module = args[0];
  3082. if (module.startsWith('ad')) {
  3083. console.log('Skip module:', module);
  3084. return;
  3085. }
  3086. return logger.apply(tgt, that, args);
  3087. }
  3088. };
  3089. let setMrAdd = v => {
  3090. v._name = 'mr.add';
  3091. v = new Proxy(v, addWrapper);
  3092. _add = v;
  3093. };
  3094. if ('add' in mr)
  3095. setMrAdd(mr.add);
  3096. Object.defineProperty(mr, 'add', {
  3097. get: () => _add,
  3098. set: setMrAdd
  3099. });
  3100.  
  3101. }
  3102.  
  3103. try {
  3104. let _mr;
  3105. Object.defineProperty(win, 'mr', {
  3106. enumerable: true,
  3107. get: () => _mr,
  3108. set: (v) => {
  3109. if (v === _mr)
  3110. return true;
  3111. console.log('Trapped new "mr" object.');
  3112. defineLocator(v.mimic ? v.mimic : v);
  3113. defineDetector(v);
  3114. defineAdd(v);
  3115. _mr = v;
  3116. }
  3117. });
  3118. if (!('mr' in win))
  3119. throw 'Wat!?';
  3120. } catch (e) {
  3121. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  3122. defineLocator(win.mr);
  3123. defineDetector(win.mr);
  3124. defineAdd(win.mr);
  3125. }
  3126.  
  3127. // smokyTools wrapper for news.mail.ru
  3128. nt.define(win, 'smokyTools', nt.proxy({
  3129. Selector: nt.func(null),
  3130. getDict: nt.func(nt.proxy({
  3131. attrLookup: nt.func(null),
  3132. classLookup: nt.func(null)
  3133. })),
  3134. CSS: nt.func(nt.proxy({
  3135. addAllCssToIndex: nt.func(null),
  3136. addCssToIndex: nt.func(null),
  3137. smokeClass: nt.func(null)
  3138. }))
  3139. }));
  3140. nt.define(win, 'smoky', nt.func(null));
  3141. nt.define(win, 'smokySingleElement', nt.func(null));
  3142. nt.define(win, 'smokyByClass', nt.func(null));
  3143. }, nullTools)
  3144. };
  3145.  
  3146. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3147. let _rmpGlobals = void 0;
  3148. Object.defineProperty(win, 'rmpGlobals', {
  3149. get: () => _rmpGlobals,
  3150. set: x => {
  3151. if (x === _rmpGlobals)
  3152. return true;
  3153. _rmpGlobals = new Proxy(x, {
  3154. get: (obj, name) => {
  3155. if (name === 'adBlockerDetected')
  3156. return false;
  3157. return obj[name];
  3158. },
  3159. set: (obj, name, val) => {
  3160. if (name === 'adBlockerDetected')
  3161. console.warn('rmpGlobals.adBlockerDetected =', val)
  3162. else
  3163. obj[name] = val;
  3164. return true;
  3165. }
  3166. });
  3167. }
  3168. });
  3169. });
  3170.  
  3171. scripts['megogo.net'] = {
  3172. now: () => {
  3173. let nt = new nullTools();
  3174. nt.define(win, 'adBlock', false);
  3175. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3176. }
  3177. };
  3178.  
  3179. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3180.  
  3181. scripts['newdeaf-online.net'] = {
  3182. dom: () => {
  3183. let adNodes = _document.querySelectorAll('.ads');
  3184. if (!adNodes)
  3185. return;
  3186. let getter = x => {
  3187. let val = x;
  3188. return () => (console.warn('read .ads', name, val), val);
  3189. };
  3190. let setter = x => console.warn('skip write .ads', name, x);
  3191. for (let adNode of adNodes)
  3192. for (let name of ['innerHTML'])
  3193. Object.defineProperty(adNode, name, {
  3194. get: getter(ads[name]),
  3195. set: setter
  3196. });
  3197. }
  3198. };
  3199.  
  3200. scripts['pb.wtf'] = {
  3201. other: ['piratbit.org', 'piratbit.ru'],
  3202. dom: () => {
  3203. // line above topic content and images in the slider in the header
  3204. let remove = node => (console.log('removed', node), node.parentNode.removeChild(node));
  3205. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3206. if (location.hostname === el.hostname &&
  3207. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3208. remove(el.closest('div, tr'));
  3209. continue;
  3210. }
  3211. // ads in the topic header in case filter above wasn't enough
  3212. let parent = el.closest('tr');
  3213. if (parent) {
  3214. let span = (parent.querySelector('span') || {}).textContent;
  3215. span && span.startsWith('YO!') && remove(parent);
  3216. }
  3217. }
  3218. // casino ad button in random places
  3219. for (let el of _document.querySelectorAll('.btn-group')) {
  3220. el = el.parentNode;
  3221. if (el.tagName === 'CENTER')
  3222. remove(el.parentNode);
  3223. }
  3224. // ads in comments
  3225. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3226. if (el && el.parentNode.children[2] == el)
  3227. remove(el);
  3228. }
  3229. };
  3230.  
  3231. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3232.  
  3233. scripts['peka2.tv'] = () => {
  3234. let bodyClass = 'body--branding';
  3235. let checkNode = node => {
  3236. for (let className of node.classList)
  3237. if (className.includes('banner') || className === bodyClass) {
  3238. _removeAttribute(node, 'style');
  3239. node.classList.remove(className);
  3240. for (let attr of Array.from(node.attributes))
  3241. if (attr.name.startsWith('advert'))
  3242. _removeAttribute(node, attr.name);
  3243. }
  3244. };
  3245. (new MutationObserver(ms => {
  3246. let m, node;
  3247. for (m of ms) for (node of m.addedNodes)
  3248. if (node instanceof HTMLElement)
  3249. checkNode(node);
  3250. })).observe(_de, {childList: true, subtree: true});
  3251. (new MutationObserver(ms => {
  3252. for (let m of ms)
  3253. checkNode(m.target);
  3254. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3255. };
  3256.  
  3257. scripts['qrz.ru'] = {
  3258. now: () => {
  3259. let nt = new nullTools();
  3260. nt.define(win, 'ab', false);
  3261. nt.define(win, 'tryMessage', nt.func(null));
  3262. }
  3263. };
  3264.  
  3265. scripts['razlozhi.ru'] = {
  3266. now: () => {
  3267. for (let func of ['createShadowRoot', 'attachShadow'])
  3268. if (func in _Element.prototype)
  3269. _Element.prototype[func] = function(){
  3270. return this.cloneNode();
  3271. };
  3272. }
  3273. };
  3274.  
  3275. scripts['rbc.ru'] = {
  3276. now: () => {
  3277. selectiveCookies('adb_on');
  3278. let _RA = void 0;
  3279. let setArgs = {
  3280. 'showBanners': false,
  3281. 'showAds': true, // used in 'checkad', triggers it if set to false
  3282. 'paywall.user.logined': true,
  3283. 'paywall.user.paid': true,
  3284. 'banners.staticPath': '',
  3285. 'paywall.staticPath': '',
  3286. 'banners.dfp.config': [],
  3287. 'banners.dfp.pageTargeting': () => null,
  3288. };
  3289. Object.defineProperty(win, 'RA', {
  3290. get: () => _RA,
  3291. set: vl => {
  3292. console.log('RA =', vl);
  3293. _RA = new Proxy(vl, {
  3294. set: (o, name, val) => {
  3295. if (name === 'config') {
  3296. console.log('RA.config =', val);
  3297. if ('set' in val)
  3298. val.set = new Proxy(val.set, {
  3299. apply: (set, that, args) => {
  3300. let name = args[0];
  3301. if (name in setArgs)
  3302. args[1] = setArgs[name];
  3303. if (name in setArgs || name === 'checkad')
  3304. console.log('RA.config.set(', ...args, ')');
  3305. return Reflect.apply(set, that, args);
  3306. }
  3307. });
  3308. }
  3309. o[name] = val;
  3310. return true;
  3311. }
  3312. });
  3313. }
  3314. });
  3315. Object.defineProperty(win, 'bannersConfig', {
  3316. get: () => [], set: () => null
  3317. });
  3318. },
  3319. dom: () => {
  3320. function cleaner(nodes) {
  3321. for (let node of nodes) {
  3322. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  3323. continue;
  3324. node.classList.remove('js-yandex-counter');
  3325. node.removeAttribute('data-yandex-name');
  3326. node.removeAttribute('data-yandex-params');
  3327. }
  3328. }
  3329. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  3330.  
  3331. (new MutationObserver(
  3332. ms => {
  3333. for (let m of ms) cleaner(m.addedNodes);
  3334. }
  3335. )).observe(_de, {childList: true, subtree: true});
  3336. }
  3337. };
  3338.  
  3339. scripts['rp5.ru'] = {
  3340. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3341. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3342. };
  3343.  
  3344. scripts['rutube.ru'] = () => scriptLander(() => {
  3345. let _parse = JSON.parse;
  3346. let _skip_enabled = false;
  3347. JSON.parse = (...args) => {
  3348. let res = _parse(...args),
  3349. log = false;
  3350. if (!res)
  3351. return res;
  3352. // parse player configuration
  3353. if ('appearance' in res || 'video_balancer' in res) {
  3354. log = true;
  3355. if (res.appearance) {
  3356. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3357. res.appearance.forbid_seek = false;
  3358. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3359. res.appearance.forbid_timeline_preview = false;
  3360. }
  3361. _skip_enabled = !!res.remove_unseekable_blocks;
  3362. //res.advert = [];
  3363. delete res.advert;
  3364. //for (let limit of res.limits)
  3365. // limit.limit = 0;
  3366. delete res.limits;
  3367. //res.yast = null;
  3368. //res.yast_live_online = null;
  3369. delete res.yast;
  3370. delete res.yast_live_online;
  3371. Object.defineProperty(res, 'stat', {
  3372. get: () => [],
  3373. set: () => true,
  3374. enumerable: true
  3375. });
  3376. }
  3377.  
  3378. // parse video configuration
  3379. if ('video_url' in res) {
  3380. log = true;
  3381. if (res.cuepoints && !_skip_enabled)
  3382. for (let point of res.cuepoints) {
  3383. point.is_pause = false;
  3384. point.show_navigation = true;
  3385. point.forbid_seek = false;
  3386. }
  3387. }
  3388.  
  3389. if (log)
  3390. console.log('[rutube]', res);
  3391. return res;
  3392. };
  3393. });
  3394.  
  3395. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3396. let _addEventListener = _Document.prototype.addEventListener;
  3397. _document.addEventListener = function(event, callback) {
  3398. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3399. return;
  3400. return _addEventListener.apply(this, arguments);
  3401. };
  3402. });
  3403.  
  3404. scripts['smotret-anime.ru'] = () => scriptLander(() => {
  3405. deepWrapAPI(root => {
  3406. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3407. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3408. let stopper = e => _pause(e.target);
  3409. root.Audio = new Proxy(root.Audio, {
  3410. construct: (audio, args) => {
  3411. let res = new audio(...args);
  3412. _addEventListener(res, 'play', stopper, true);
  3413. return res;
  3414. }
  3415. });
  3416. _createElement = root.Document.prototype.createElement;
  3417. root.Document.prototype.createElement = function createElement() {
  3418. let res = _createElement.apply(this, arguments);
  3419. if (res instanceof HTMLAudioElement)
  3420. _addEventListener(res, 'play', stopper, true);
  3421. return res;
  3422. };
  3423. });
  3424. }, deepWrapAPI);
  3425.  
  3426. scripts['spaces.ru'] = () => {
  3427. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3428. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3429. };
  3430.  
  3431. scripts['spam-club.blogspot.co.uk'] = () => {
  3432. let _clientHeight = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientHeight'),
  3433. _clientWidth = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientWidth');
  3434. let wrapGetter = (getter) => {
  3435. let _getter = getter;
  3436. return function() {
  3437. let _size = _getter.apply(this, arguments);
  3438. return _size ? _size : 1;
  3439. };
  3440. };
  3441. _clientHeight.get = wrapGetter(_clientHeight.get);
  3442. _clientWidth.get = wrapGetter(_clientWidth.get);
  3443. Object.defineProperty(_Element.prototype, 'clientHeight', _clientHeight);
  3444. Object.defineProperty(_Element.prototype, 'clientWidth', _clientWidth);
  3445. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3446. _set_onload = _onload.set;
  3447. _onload.set = function() {
  3448. if (this instanceof HTMLImageElement)
  3449. return true;
  3450. _set_onload.apply(this, arguments);
  3451. };
  3452. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3453. };
  3454.  
  3455. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3456.  
  3457. scripts['sports.ru'] = {
  3458. now: () => {
  3459. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3460. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3461. // extra functionality: shows/hides panel at the top depending on scroll direction
  3462. createStyle([
  3463. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3464. '.user-panel-up { top: -40px!important }'
  3465. ], {id: 'userPanelSlide'}, false);
  3466. },
  3467. dom: () => {
  3468. (function lookForPanel() {
  3469. let panel = _document.querySelector('.user-panel__fixed');
  3470. if (!panel)
  3471. setTimeout(lookForPanel, 100);
  3472. else
  3473. window.addEventListener(
  3474. 'wheel', function(e) {
  3475. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3476. panel.classList.add('user-panel-up');
  3477. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3478. panel.classList.remove('user-panel-up');
  3479. }, false
  3480. );
  3481. })();
  3482. }
  3483. };
  3484.  
  3485. scripts['stealthz.ru'] = {
  3486. dom: () => {
  3487. // skip timeout
  3488. let $ = _document.querySelector.bind(_document);
  3489. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3490. if (!timer_1 || !timer_2)
  3491. return;
  3492. timer_1.style.display = 'none';
  3493. timer_2.style.display = 'block';
  3494. }
  3495. };
  3496.  
  3497. scripts['xittv.net'] = () => scriptLander(() => {
  3498. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  3499. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  3500. let _jwplayer = void 0;
  3501. Object.defineProperty(win, 'jwplayer', {
  3502. get: () => _jwplayer,
  3503. set: x => {
  3504. _jwplayer = new Proxy(x, {
  3505. apply: (fun, that, args) => {
  3506. let res = fun.apply(that, args);
  3507. res = new Proxy(res, {
  3508. get: (obj, name) => {
  3509. if (logNames.includes(name) && obj[name] instanceof Function)
  3510. return new Proxy(obj[name], {
  3511. apply: (fun, that, args) => {
  3512. if (name === 'setup') {
  3513. let o = args[0];
  3514. if (o)
  3515. delete o.advertising;
  3516. }
  3517. if (name === 'on' || name === 'trigger') {
  3518. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  3519. if (events.length === 1 && skipEvents.includes(events[0]))
  3520. return res;
  3521. if (events.length > 1) {
  3522. let names = [];
  3523. for (let event of events)
  3524. if (!skipEvents.includes(event))
  3525. names.push(event);
  3526. if (names.length > 0)
  3527. args[0] = names.join(" ");
  3528. else
  3529. return res;
  3530. }
  3531. }
  3532. let subres = fun.apply(that, args);
  3533. console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  3534. return subres;
  3535. }
  3536. });
  3537. return obj[name];
  3538. }
  3539. });
  3540. return res;
  3541. }
  3542. });
  3543. console.log('jwplayer =', x);
  3544. }
  3545. });
  3546. });
  3547.  
  3548. scripts['yap.ru'] = {
  3549. other: ['yaplakal.com'],
  3550. now: () => {
  3551. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3552. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3553. }
  3554. };
  3555.  
  3556. scripts['rambler.ru'] = {
  3557. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  3558. now: () => scriptLander(() => {
  3559. // Prevent autoplay
  3560. if (!('EaglePlayer' in win)) {
  3561. let _EaglePlayer = void 0;
  3562. Object.defineProperty(win, 'EaglePlayer', {
  3563. enumerable: true,
  3564. get: () => _EaglePlayer,
  3565. set: x => {
  3566. if (x === _EaglePlayer)
  3567. return true;
  3568. _EaglePlayer = new Proxy(x, {
  3569. construct: (targ, args) => {
  3570. let player = new targ(...args);
  3571. if (!player.options) {
  3572. console.log('EaglePlayer: no options', EaglePlayer);
  3573. return player;
  3574. }
  3575. Object.defineProperty(player.options, 'autoplay', {
  3576. get: () => false,
  3577. set: () => true
  3578. });
  3579. Object.defineProperty(player.options, 'scroll', {
  3580. get: () => false,
  3581. set: () => true
  3582. });
  3583. return player;
  3584. }
  3585. });
  3586. }
  3587. });
  3588. let _setAttribute = Function.prototype.apply.bind(_Element.prototype.setAttribute);
  3589. let isAutoplay = /^autoplay$/i;
  3590. _Element.prototype.setAttribute = function setAttribute(name) {
  3591. if (!this._stopped && isAutoplay.test(name)) {
  3592. console.log('Prevented assigning autoplay attribute.');
  3593. return null;
  3594. }
  3595. return _setAttribute(this, arguments);
  3596. };
  3597. } else {
  3598. console.log('EaglePlayer function already exists.');
  3599. if (inIFrame) {
  3600. let _setAttribute = Function.prototype.apply.bind(_Element.prototype.setAttribute);
  3601. let isAutoplay = /^autoplay$/i;
  3602. _Element.prototype.setAttribute = function setAttribute(name) {
  3603. if (!this._stopped && isAutoplay.test(name)) {
  3604. console.log('Prevented assigning autoplay attribute.');
  3605. this._stopped = true;
  3606. this.play = () => {
  3607. console.log('Prevented attempt to force-start playback.');
  3608. delete this.play;
  3609. };
  3610. return null;
  3611. }
  3612. return _setAttribute(this, arguments);
  3613. };
  3614. }
  3615. }
  3616. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3617. return;
  3618. // prevent ads from loading
  3619. let blockObfuscated = false;
  3620. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  3621. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3622. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3623. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3624. let _cssText_get = _cssText.get;
  3625. _cssText.configurable = false;
  3626. _cssText.get = function() {
  3627. let cssText = _cssText_get.call(this);
  3628. if (cssText.includes('content:')) {
  3629. console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3630. blockObfuscated = true;
  3631. return null;
  3632. }
  3633. return cssText;
  3634. };
  3635. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3636. let _setTimeout = win.setTimeout;
  3637. win.setTimeout = function(f) {
  3638. if (blockObfuscated && obfuscation.test(_toString(f))) {
  3639. console.warn('Stopped setTimeout for:', _toString(f).slice(0,100), '\u2026');
  3640. return null;
  3641. };
  3642. return _setTimeout.apply(this, arguments);
  3643. };
  3644. // fake global Adf object
  3645. let nt = new nullTools();
  3646. let Adf_banner = {};
  3647. [
  3648. 'reloadssp', 'sspScroll',
  3649. 'sspRich', 'ssp'
  3650. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3651. nt.define(win, 'Adf', nt.proxy({
  3652. banner: nt.proxy(Adf_banner)
  3653. }));
  3654. // extra script to remove partner news on gazeta.ru
  3655. if (!location.hostname.includes('gazeta.ru'))
  3656. return;
  3657. (new MutationObserver(
  3658. (ms) => {
  3659. let m, node, header;
  3660. for (m of ms) for (node of m.addedNodes)
  3661. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3662. header = node.querySelector('.sausage-header');
  3663. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3664. node.style.display = 'none';
  3665. }
  3666. }
  3667. )).observe(_document.documentElement, { childList:true, subtree: true });
  3668. }, `let inIFrame = ${inIFrame}`, nullTools)
  3669. };
  3670.  
  3671. scripts['reactor.cc'] = {
  3672. other: ['joyreactor.cc', 'pornreactor.cc'],
  3673. now: () => {
  3674. selectiveEval();
  3675. scriptLander(() => {
  3676. let nt = new nullTools();
  3677. win.open = function(){
  3678. throw new Error('Redirect prevention.');
  3679. };
  3680. nt.define(win, 'Worker', function(){});
  3681. nt.define(win, 'JRCH', win.CoinHive);
  3682. }, nullTools);
  3683. },
  3684. click: function(e) {
  3685. let node = e.target;
  3686. if (node.nodeType === _Node.ELEMENT_NODE &&
  3687. node.style.position === 'absolute' &&
  3688. node.style.zIndex > 0)
  3689. node.parentNode.removeChild(node);
  3690. },
  3691. dom: function() {
  3692. let words = new RegExp(
  3693. 'блокировщик рекламы'
  3694. .split('')
  3695. .map(function(e){
  3696. return e+'[\u200b\u200c\u200d]*';
  3697. })
  3698. .join('')
  3699. .replace(' ', '\\s*')
  3700. .replace(/[аоре]/g, function(e){
  3701. return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];
  3702. }),
  3703. 'i'),
  3704. can;
  3705. function deeper(spider) {
  3706. for (let child of spider.childNodes)
  3707. if (words.test(child.innerText))
  3708. if (child.offsetHeight >= 750)
  3709. deeper(child);
  3710. else
  3711. can.push(child);
  3712. }
  3713. function probe() {
  3714. can = [];
  3715. deeper(_document.body);
  3716. for (let spider of can)
  3717. _setAttribute(spider, 'style', 'background:none!important');
  3718. }
  3719. (new MutationObserver(probe))
  3720. .observe(_document, { childList:true, subtree:true });
  3721. }
  3722. };
  3723.  
  3724. scripts['auto.ru'] = () => {
  3725. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3726. let userAdsListAds = (
  3727. '.listing-list > .listing-item,'+
  3728. '.listing-item_type_fixed.listing-item'
  3729. );
  3730. let catalogAds = (
  3731. 'div[class*="layout_catalog-inline"],'+
  3732. 'div[class$="layout_horizontal"]'
  3733. );
  3734. let otherAds = (
  3735. '.advt_auto,'+
  3736. '.sidebar-block,'+
  3737. '.pager-listing + div[class],'+
  3738. '.card > div[class][style],'+
  3739. '.sidebar > div[class],'+
  3740. '.main-page__section + div[class],'+
  3741. '.listing > tbody'
  3742. );
  3743. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3744. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3745. gardener(otherAds, words);
  3746. };
  3747.  
  3748. scripts['rsload.net'] = {
  3749. load: () => {
  3750. let dis = _document.querySelector('label[class*="cb-disable"]');
  3751. if (dis)
  3752. dis.click();
  3753. },
  3754. click: e => {
  3755. let t = e.target;
  3756. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3757. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3758. }
  3759. };
  3760.  
  3761. let domain;
  3762. // add alternative domain names if present and wrap functions into objects
  3763. for (let name in scripts) {
  3764. if (scripts[name] instanceof Function)
  3765. scripts[name] = { now: scripts[name] };
  3766. for (domain of (scripts[name].other||[])) {
  3767. if (domain in scripts)
  3768. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3769. scripts[domain] = scripts[name];
  3770. }
  3771. delete scripts[name].other;
  3772. }
  3773. // look for current domain in the list and run appropriate code
  3774. domain = _document.domain;
  3775. while (domain.includes('.')) {
  3776. if (domain in scripts) for (let when in scripts[domain])
  3777. switch(when) {
  3778. case 'now':
  3779. scripts[domain][when]();
  3780. break;
  3781. case 'dom':
  3782. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3783. break;
  3784. default:
  3785. _document.addEventListener (when, scripts[domain][when], false);
  3786. }
  3787. domain = domain.slice(domain.indexOf('.') + 1);
  3788. }
  3789.  
  3790. // Batch script lander
  3791. if (!skipLander)
  3792. landScript(batchLand, batchPrepend);
  3793.  
  3794. { // JS Fixes Tools Menu
  3795. let openOptions = function() {
  3796. let ovl = _createElement('div'),
  3797. inner = _createElement('div');
  3798. ovl.style = (
  3799. 'position: fixed;'+
  3800. 'top:0; left:0;'+
  3801. 'bottom: 0; right: 0;'+
  3802. 'background: rgba(0,0,0,0.85);'+
  3803. 'z-index: 2147483647;'+
  3804. 'padding: 5em'
  3805. );
  3806. inner.style = (
  3807. 'background: whitesmoke;'+
  3808. 'font-size: 10pt;'+
  3809. 'color: black;'+
  3810. 'padding: 1em'
  3811. );
  3812. inner.textContent = 'JS Fixes Tools';
  3813. inner.appendChild(_createElement('br'));
  3814. inner.appendChild(_createElement('br'));
  3815. ovl.addEventListener(
  3816. 'click', function(e) {
  3817. if (e.target === ovl) {
  3818. ovl.parentNode.removeChild(ovl);
  3819. e.preventDefault();
  3820. }
  3821. e.stopPropagation();
  3822. }, false
  3823. );
  3824.  
  3825. let sObjBtn = _createElement('button');
  3826. sObjBtn.onclick = getStrangeObjectsList;
  3827. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  3828. inner.appendChild(_createElement('br'));
  3829. inner.appendChild(sObjBtn);
  3830.  
  3831. _document.body.appendChild(ovl);
  3832. ovl.appendChild(inner);
  3833. };
  3834.  
  3835. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  3836. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  3837. _document.addEventListener(
  3838. 'keydown', function(e) {
  3839. if ((e.code === opKey[opPos] || e.location) &&
  3840. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  3841. opPos += e.location ? 0 : 1;
  3842. e.stopPropagation();
  3843. e.preventDefault();
  3844. } else
  3845. opPos = 0;
  3846. if (opPos === opKey.length) {
  3847. opPos = 0;
  3848. openOptions();
  3849. }
  3850. }, false
  3851. );
  3852. }
  3853. })();