RU AdList JS Fixes

try to take over the world!

目前為 2018-12-25 提交的版本,檢視 最新版本

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