RU AdList JS Fixes

try to take over the world!

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

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