RU AdList JS Fixes

try to take over the world!

目前为 2018-11-29 提交的版本。查看 最新版本

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