RU AdList JS Fixes

try to take over the world!

当前为 2018-11-08 提交的版本,查看 最新版本

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