RU AdList JS Fixes

try to take over the world!

当前为 2018-12-20 提交的版本,查看 最新版本

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