RU AdList JS Fixes

try to take over the world!

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

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