RU AdList JS Fixes

try to take over the world!

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

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