RU AdList JS Fixes

try to take over the world!

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

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20181224.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/.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. }
  2583. return Reflect.apply(module, that, args);
  2584. }
  2585. });
  2586. }
  2587. di[name] = vl;
  2588. return true;
  2589. }
  2590. });
  2591. }
  2592. });
  2593. // don't send errorception logs
  2594. Object.defineProperty(win, 'onerror', {
  2595. set: vl => log && _console.warn('Skipped global onerror callback', vl)
  2596. });
  2597. });
  2598.  
  2599. scripts['drive2.ru'] = () => {
  2600. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2601. scriptLander(() => {
  2602. let _d2 = void 0;
  2603. Object.defineProperty(win, 'd2', {
  2604. get: () => _d2,
  2605. set: o => {
  2606. if (o === _d2)
  2607. return true;
  2608. _d2 = new Proxy(o, {
  2609. set: (tgt, prop, val) => {
  2610. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2611. val = () => null;
  2612. tgt[prop] = val;
  2613. return true;
  2614. }
  2615. });
  2616. }
  2617. });
  2618. });
  2619. };
  2620.  
  2621. scripts['fastpic.ru'] = () => {
  2622. let nt = new nullTools();
  2623. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2624. nt.define(win, `_0x${'4955'}`, []);
  2625. };
  2626.  
  2627. scripts['fishki.net'] = () => {
  2628. scriptLander(() => {
  2629. let nt = new nullTools();
  2630. let fishki = {};
  2631. nt.define(fishki, 'adv', nt.proxy({
  2632. afterAdblockCheck: nt.func(null),
  2633. refreshFloat: nt.func(null)
  2634. }));
  2635. nt.define(fishki, 'is_adblock', false);
  2636. nt.define(win, 'fishki', fishki);
  2637. }, nullTools);
  2638. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2639. };
  2640.  
  2641. scripts['friends.in.ua'] = () => scriptLander(() => {
  2642. Object.defineProperty(win, 'need_warning', {
  2643. get: () => 0, set: () => null
  2644. });
  2645. });
  2646.  
  2647. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2648.  
  2649. scripts['hdgo.cc'] = {
  2650. other: ['46.30.43.38', 'couber.be'],
  2651. now: () => (new MutationObserver(
  2652. (ms) => {
  2653. let m, node;
  2654. for (m of ms) for (node of m.addedNodes)
  2655. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2656. node.removeAttribute('onerror');
  2657. }
  2658. )).observe(_document.documentElement, { childList:true, subtree: true })
  2659. };
  2660.  
  2661. scripts['gismeteo.ru'] = {
  2662. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2663. now: () => {
  2664. selectiveCookies('ab_[^=]*|bltsr|redirect|_gab');
  2665. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2666. }
  2667. };
  2668.  
  2669. scripts['hdrezka.ag'] = () => {
  2670. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2671. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2672. };
  2673.  
  2674. scripts['hqq.tv'] = () => scriptLander(() => {
  2675. // disable anti-debugging in hqq.tv player
  2676. 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);
  2677. deepWrapAPI(root => {
  2678. // skip obfuscated stuff and a few other calls
  2679. let _setInterval = root.setInterval,
  2680. _setTimeout = root.setTimeout,
  2681. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2682. root.setInterval = (...args) => {
  2683. let fun = args[0];
  2684. if (fun instanceof Function) {
  2685. let text = _toString(fun),
  2686. skip = text.includes('check();') || isObfuscated(text);
  2687. _console.warn('setInterval', text, 'skip', skip);
  2688. if (skip) return -1;
  2689. }
  2690. return _setInterval.apply(this, args);
  2691. };
  2692. let wrappedST = new WeakSet();
  2693. root.setTimeout = (...args) => {
  2694. let fun = args[0];
  2695. if (fun instanceof Function) {
  2696. let text = _toString(fun),
  2697. skip = fun.name === 'check' || isObfuscated(text);
  2698. if (!wrappedST.has(fun)) {
  2699. _console.warn('setTimeout', text, 'skip', skip);
  2700. wrappedST.add(fun);
  2701. }
  2702. if (skip) return;
  2703. }
  2704. return _setTimeout.apply(this, args);
  2705. };
  2706. // skip 'debugger' call
  2707. let _eval = root.eval;
  2708. root.eval = text => {
  2709. if (typeof text === 'string' && text.includes('debugger;')) {
  2710. _console.warn('skip eval', text);
  2711. return;
  2712. }
  2713. _eval(text);
  2714. };
  2715. // Prevent RegExpt + toString trick
  2716. let _proto = void 0;
  2717. try {
  2718. _proto = root.RegExp.prototype;
  2719. } catch(ignore) {
  2720. return;
  2721. }
  2722. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  2723. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  2724. Object.defineProperty(_proto, 'toString', {
  2725. enumerable: _RE_tS.enumerable,
  2726. configurable: _RE_tS.configurable,
  2727. get: () => _RE_tSV,
  2728. set: val => _console.warn('Attempt to change toString for', this, 'with', _toString(val))
  2729. });
  2730. });
  2731. }, deepWrapAPI);
  2732.  
  2733. scripts['hideip.me'] = {
  2734. now: () => scriptLander(() => {
  2735. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  2736. let _set_innerHTML = _innerHTML.set;
  2737. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2738. let _get_innerText = _innerText.get;
  2739. let div = _document.createElement('div');
  2740. _innerHTML.set = function(...args) {
  2741. _set_innerHTML.call(div, args[0].replace('i','a'));
  2742. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2743. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2744. _console.log('Anti-Adblock killed.');
  2745. return true;
  2746. }
  2747. _set_innerHTML.apply(this, args);
  2748. };
  2749. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  2750. Object.defineProperty(win, 'adblock', {
  2751. get: () => false,
  2752. set: () => null,
  2753. enumerable: true
  2754. });
  2755. let _$ = {};
  2756. let _$_map = new WeakMap();
  2757. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2758. let _val_gOPD = _gOPD.value;
  2759. _gOPD.value = function(...args) {
  2760. let _res = _val_gOPD.apply(this, args);
  2761. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2762. delete _res.get;
  2763. delete _res.set;
  2764. _res.value = win[args[1]];
  2765. }
  2766. return _res;
  2767. };
  2768. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2769. let getJQWrap = (n) => {
  2770. let name = n;
  2771. return {
  2772. enumerable: true,
  2773. get: () => _$[name],
  2774. set: x => {
  2775. if (_$_map.has(x)) {
  2776. _$[name] = _$_map.get(x);
  2777. return true;
  2778. }
  2779. if (x === _$.$ || x === _$.jQuery) {
  2780. _$[name] = x;
  2781. return true;
  2782. }
  2783. _$[name] = new Proxy(x, {
  2784. apply: (t, o, args) => {
  2785. let _res = t.apply(o, args);
  2786. if (_$_map.has(_res.is))
  2787. _res.is = _$_map.get(_res.is);
  2788. else {
  2789. let _is = _res.is;
  2790. _res.is = function(...args) {
  2791. if (args[0] === ':hidden')
  2792. return false;
  2793. return _is.apply(this, args);
  2794. };
  2795. _$_map.set(_is, _res.is);
  2796. }
  2797. return _res;
  2798. }
  2799. });
  2800. _$_map.set(x, _$[name]);
  2801. return true;
  2802. }
  2803. };
  2804. };
  2805. Object.defineProperty(win, '$', getJQWrap('$'));
  2806. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2807. let _dP = Object.defineProperty;
  2808. Object.defineProperty = function(...args) {
  2809. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2810. return void 0;
  2811. return _dP.apply(this, args);
  2812. };
  2813. })
  2814. };
  2815.  
  2816. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2817. let nt = new nullTools();
  2818. /*jslint evil: true */ // yes, evil, I know
  2819. let _write = _document.write.bind(_document);
  2820. /*jslint evil: false */
  2821. nt.define(_document, 'write', t => {
  2822. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2823. if (id && id[1])
  2824. return _write(`<div id="${id[1]}"></div>${t}`);
  2825. return _write('');
  2826. });
  2827. });
  2828.  
  2829. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  2830.  
  2831. scripts['ivi.ru'] = () => {
  2832. let _xhr_open = win.XMLHttpRequest.prototype.open;
  2833. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  2834. if (typeof url === 'string')
  2835. if (url.endsWith('/track'))
  2836. return;
  2837. return _xhr_open.call(this, method, url, ...args);
  2838. };
  2839. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  2840. let _responseText_get = _responseText.get;
  2841. _responseText.get = function() {
  2842. if (this.__responseText__)
  2843. return this.__responseText__;
  2844. let res = _responseText_get.apply(this, arguments);
  2845. let o;
  2846. try {
  2847. if (res)
  2848. o = JSON.parse(res);
  2849. } catch(ignore) {};
  2850. let changed = false;
  2851. if (o && o.result) {
  2852. if (o.result instanceof Array &&
  2853. 'adv_network_logo_url' in o.result[0]) {
  2854. o.result = [];
  2855. changed = true;
  2856. }
  2857. if (o.result.show_adv) {
  2858. o.result.show_adv = false;
  2859. changed = true;
  2860. }
  2861. }
  2862. if (changed) {
  2863. _console.log('changed response >>', o);
  2864. res = JSON.stringify(o);
  2865. }
  2866. this.__responseText__ = res;
  2867. return res;
  2868. };
  2869. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  2870. };
  2871.  
  2872. scripts['kinopoisk.ru'] = () => {
  2873. selectiveCookies('bltsr|cmtchd|crookie|kpunk');
  2874. // set no-branding body style and adjust other blocks on the page
  2875. let style = [
  2876. '.app__header.app__header_margin-bottom_brand, #top { margin-bottom: 20px !important }',
  2877. '.app__branding { display: none !important}'
  2878. ];
  2879. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  2880. style.push('html:not(#id), body:not(#id), .app-container { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2881. createStyle(style);
  2882. // catch branding and other things
  2883. let _KP = void 0;
  2884. Object.defineProperty(win, 'KP', {
  2885. get: () => _KP,
  2886. set: val => {
  2887. if (_KP === val)
  2888. return true;
  2889. _KP = new Proxy(val, {
  2890. set: (kp, name, val) => {
  2891. if (name === 'branding') {
  2892. kp[name] = new Proxy({ weborama: {} }, {
  2893. get: (kp, name) => name in kp ? kp[name] : '',
  2894. set: () => true
  2895. });
  2896. return true;
  2897. }
  2898. if (name === 'config')
  2899. val = new Proxy(val, {
  2900. set: (cfg, name, val) => {
  2901. if (name === 'anContextUrl')
  2902. return true;
  2903. if (name === 'adfoxEnabled' || name === 'hasBranding')
  2904. val = false;
  2905. if (name === 'adfoxVideoAdUrls')
  2906. val = {flash:{}, html:{}};
  2907. cfg[name] = val;
  2908. return true;
  2909. }
  2910. });
  2911. kp[name] = val;
  2912. return true;
  2913. }
  2914. });
  2915. _console.log('KP =', val);
  2916. }
  2917. });
  2918. // skip branding and some other junk
  2919. Object.defineProperty(win, 'advBlock', {
  2920. get: () => () => null,
  2921. set: () => true
  2922. });
  2923. // skip timeout check for blocked requests
  2924. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  2925. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2926. win.setTimeout = function(...args) {
  2927. if (args[1] === 100) {
  2928. let str = _toString(args[0]);
  2929. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  2930. return;
  2931. }
  2932. return _setTimeout(this, args);
  2933. };
  2934. };
  2935.  
  2936. scripts['kinozal-tv.appspot.com'] = {
  2937. other: ['a-dot-kinozal-tv.appspot.com'],
  2938. now: () => {
  2939. // They check if 'startsWith' in String.prototype
  2940. // and skip parts of ABP detector if it's not there
  2941. delete String.prototype.startsWith;
  2942. }
  2943. };
  2944.  
  2945. scripts['korrespondent.net'] = {
  2946. now: () => scriptLander(() => {
  2947. let nt = new nullTools();
  2948. nt.define(win, 'holder', function(id) {
  2949. let div = _document.getElementById(id);
  2950. if (!div)
  2951. return;
  2952. if (div.parentNode.classList.contains('col__sidebar')) {
  2953. div.parentNode.appendChild(div);
  2954. div.style.height = '300px';
  2955. }
  2956. });
  2957. }, nullTools),
  2958. dom: () => {
  2959. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  2960. frame.parentNode.style.width = '1px';
  2961. }
  2962. };
  2963.  
  2964. scripts['mail.ru'] = {
  2965. other: ['ok.ru'],
  2966. now: () => {
  2967. selectiveCookies('act|s|t|p|testcookie');
  2968. scriptLander(() => {
  2969. let nt = new nullTools();
  2970. // Trick to prevent mail.ru from removing 3rd-party styles
  2971. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2972. // Disable some of their counters
  2973. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2974. if (location.hostname === 'e.mail.ru')
  2975. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2976. else
  2977. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2978.  
  2979. {
  2980. let missingCheck = {
  2981. get: (obj, name) => {
  2982. if (!(name in obj))
  2983. _console.warn(obj, 'missing:', name);
  2984. return obj[name];
  2985. }
  2986. };
  2987. let skipLog = (name, ret) => (...args) => (_console.log(`Skip ${name}(`, ...args, ')'), ret);
  2988. let createSkipLogObject = (baseName, list) => list.reduce(
  2989. (acc, cur) => (acc[cur] = skipLog(`${baseName}.${cur}`), acc),
  2990. {}
  2991. );
  2992. let redefiner = {
  2993. apply: (target, thisArg, args) => {
  2994. let res = void 0;
  2995. if (target._name === 'mrg-smokescreen/Welter')
  2996. res = {
  2997. isWelter: () => true,
  2998. wrap: skipLog(`${target._name}.wrap`)
  2999. };
  3000. if (target._name === 'mrg-smokescreen/StyleSheets')
  3001. res = createSkipLogObject(target._name, ['update', 'remove', 'insert', 'setup']);
  3002. if (target._name === 'mrg-honeypot/main')
  3003. res = { check: skipLog(`${target._name}.check`, false) };
  3004. if (target._name.startsWith('advert/rb/slot')) {
  3005. res = createSkipLogObject(target._name, ['get', 'getHTML', 'createBlock', 'onRedirect']);
  3006. res.slot = '0';
  3007. }
  3008. if (target._name.startsWith('OK/banners/'))
  3009. res = createSkipLogObject(target._name, ['activate', 'deactivate']);
  3010. if (target._name === 'mimic') {
  3011. res = createSkipLogObject(target._name, ['insertDirect', 'setup']);
  3012. res.version = "%PACKAGE_VERSION%";
  3013. }
  3014. if (target._name === 'advert/adman/adman')
  3015. res = createSkipLogObject(target._name, ['refresh', 'getBlock', 'init']);
  3016. if (res)
  3017. res = new Proxy(res, missingCheck);
  3018. else
  3019. res = target.apply(thisArg, args);
  3020. if (target._name === 'mrg-smokescreen/Utils')
  3021. res.extend = function(...args) {
  3022. let res = {
  3023. enable: false,
  3024. match: [],
  3025. links: []
  3026. };
  3027. _console.log(`${target._name}.extend(`, ...args, ') >>', res );
  3028. return res;
  3029. };
  3030. if (target._name === 'advert/RB') {
  3031. res.getSlots = () => [];
  3032. res.load._name = target._name + '.load';
  3033. res.load = new Proxy(res.load, redefiner);
  3034. }
  3035. _console.log(target._name, '(',...args,') >>', res);
  3036. return res;
  3037. }
  3038. };
  3039.  
  3040. let wrapAdFuncs = {
  3041. apply: (target, thisArg, args) => {
  3042. let module = args[0];
  3043. if (typeof module === 'string')
  3044. if (module.startsWith('mrg-smoke') ||
  3045. module.startsWith('mrg-context') ||
  3046. module.startsWith('mrg-honeypot') ||
  3047. module.startsWith('advert') ||
  3048. module.startsWith('mimic') ||
  3049. module.startsWith('OK/banner') ||
  3050. module === 'OK/Smokescreen') {
  3051. let fun = args[args.length-1];
  3052. fun._name = module;
  3053. args[args.length-1] = new Proxy(fun, redefiner);
  3054. }// else
  3055. // _console.log('Define:', args[0]);
  3056. return target.apply(thisArg, args);
  3057. }
  3058. };
  3059. let wrapDefine = def => {
  3060. if (!def)
  3061. return;
  3062. _console.log('define =', def);
  3063. def = new Proxy(def, wrapAdFuncs);
  3064. def._name = 'define';
  3065. return def;
  3066. };
  3067. let _define = wrapDefine(win.define);
  3068. Object.defineProperty(win, 'define', {
  3069. get: () => _define,
  3070. set: x => {
  3071. if (_define === x)
  3072. return true;
  3073. _define = wrapDefine(x);
  3074. return true;
  3075. }
  3076. });
  3077. }
  3078.  
  3079. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3080. let logger = {
  3081. apply: (target, thisArg, args) => {
  3082. let res = target.apply(thisArg, args);
  3083. _console.log(`${target._name}(`, ...args, `) >>`, res);
  3084. return res;
  3085. }
  3086. };
  3087.  
  3088. let _locator;
  3089. function wrapLocator(locator) {
  3090. if ('setup' in locator) {
  3091. let _setup = locator.setup;
  3092. locator.setup = function(o) {
  3093. if ('enable' in o) {
  3094. o.enable = false;
  3095. _console.log('Disable mimic mode.');
  3096. }
  3097. if ('links' in o) {
  3098. o.links = [];
  3099. _console.log('Call with empty list of sheets.');
  3100. }
  3101. return _setup.call(this, o);
  3102. };
  3103. locator.insertSheet = () => false;
  3104. locator.wrap = () => false;
  3105. }
  3106. try {
  3107. let names = [];
  3108. for (let name in locator)
  3109. if (locator[name] instanceof Function && name !== 'transform') {
  3110. locator[name]._name = "locator." + name;
  3111. locator[name] = new Proxy(locator[name], logger);
  3112. names.push(name);
  3113. }
  3114. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3115. } catch(e) {
  3116. _console.log(e);
  3117. }
  3118. _locator = locator;
  3119. }
  3120.  
  3121. function defineLocator(root) {
  3122. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3123. if (!loc_desc || loc_desc.set !== wrapLocator)
  3124. try {
  3125. Object.defineProperty(root, 'locator', {
  3126. set: wrapLocator,
  3127. get: () => _locator
  3128. });
  3129. } catch (err) {
  3130. _console.log('Unable to redefine "locator" object!!!', err);
  3131. }
  3132. }
  3133.  
  3134. let _honeyPot;
  3135. function defineDetector(mr) {
  3136. let __ = mr._ || {};
  3137. let setHoneyPot = o => {
  3138. if (!o || o === _honeyPot) return;
  3139. _console.log('[honeyPot]', o);
  3140. _honeyPot = function() {
  3141. this.check = new Proxy(() => {
  3142. __.STUCK_IN_POT = false;
  3143. return false;
  3144. }, logger);
  3145. this.check._name = 'honeyPot.check';
  3146. this.destroy = () => null;
  3147. };
  3148. };
  3149. if ('honeyPot' in mr)
  3150. setHoneyPot(mr.honeyPot);
  3151. else
  3152. Object.defineProperty(mr, 'honeyPot', {
  3153. get: () => _honeyPot,
  3154. set: setHoneyPot
  3155. });
  3156.  
  3157. __ = new Proxy(__, {
  3158. get: (t, p) => t[p],
  3159. set: (t, p, v) => {
  3160. _console.log(`mr._.${p} =`, v);
  3161. t[p] = v;
  3162. return true;
  3163. }
  3164. });
  3165. mr._ = __;
  3166. }
  3167.  
  3168. function defineAdd(mr) {
  3169. let _add;
  3170. let addWrapper = {
  3171. apply: (tgt, that, args) => {
  3172. let module = args[0];
  3173. if (typeof module === 'string' && module.startsWith('ad')) {
  3174. _console.log('Skip module:', module);
  3175. return;
  3176. }
  3177. if (typeof module === 'object' && module.name.startsWith('ad'))
  3178. _console.log('Loaded module:', module);
  3179. return logger.apply(tgt, that, args);
  3180. }
  3181. };
  3182. let setMrAdd = v => {
  3183. if (!v) return;
  3184. v._name = 'mr.add';
  3185. v = new Proxy(v, addWrapper);
  3186. _add = v;
  3187. };
  3188. if ('add' in mr)
  3189. setMrAdd(mr.add);
  3190. Object.defineProperty(mr, 'add', {
  3191. get: () => _add,
  3192. set: setMrAdd
  3193. });
  3194.  
  3195. }
  3196.  
  3197. let _mr_wrapper = vl => {
  3198. defineLocator(vl.mimic ? vl.mimic : vl);
  3199. defineDetector(vl);
  3200. defineAdd(vl);
  3201. return vl;
  3202. };
  3203. if ('mr' in win) {
  3204. _console.log('Found existing "mr" object.');
  3205. win.mr = _mr_wrapper(win.mr);
  3206. } else {
  3207. let _mr = void 0;
  3208. Object.defineProperty(win, 'mr', {
  3209. get: () => _mr,
  3210. set: vl => { _mr = _mr_wrapper(vl) },
  3211. configurable: true
  3212. });
  3213. let _defineProperty = Function.prototype.apply.bind(Object.defineProperty);
  3214. Object.defineProperty = function defineProperty(o, name, conf) {
  3215. if (name === 'mr' && o instanceof Window) {
  3216. _console.warn('Object.defineProperty(', ...arguments, ')');
  3217. conf.set(_mr_wrapper(conf.get()));
  3218. }
  3219. if ((name === 'honeyPot' || name === 'add') && _mr === o && conf.set)
  3220. return;
  3221. return _defineProperty(this, arguments);
  3222. };
  3223. }
  3224.  
  3225. // smokyTools wrapper for news.mail.ru
  3226. nt.define(win, 'smokyTools', nt.proxy({
  3227. getDict: nt.func(nt.proxy({}, 'smokyTools.getDict', null), 'smokyTools.getDict'),
  3228. CSS: nt.func(nt.proxy({}, 'smokyTools.CSS', null), 'smokyTools.CSS')
  3229. }, 'smokyTools', null));
  3230. nt.define(win, 'smoky', nt.func(null, 'smoky'));
  3231. nt.define(win, 'smokySingleElement', nt.func(null, 'smokySingleElement'));
  3232. nt.define(win, 'smokyByClass', nt.func(null, 'smokyByClass'));
  3233. }, nullTools);
  3234. }
  3235. };
  3236.  
  3237. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3238. let _rmpGlobals = void 0;
  3239. Object.defineProperty(win, 'rmpGlobals', {
  3240. get: () => _rmpGlobals,
  3241. set: x => {
  3242. if (x === _rmpGlobals)
  3243. return true;
  3244. _rmpGlobals = new Proxy(x, {
  3245. get: (obj, name) => {
  3246. if (name === 'adBlockerDetected')
  3247. return false;
  3248. return obj[name];
  3249. },
  3250. set: (obj, name, val) => {
  3251. if (name === 'adBlockerDetected')
  3252. _console.warn('rmpGlobals.adBlockerDetected =', val)
  3253. else
  3254. obj[name] = val;
  3255. return true;
  3256. }
  3257. });
  3258. }
  3259. });
  3260. });
  3261.  
  3262. scripts['megogo.net'] = {
  3263. now: () => {
  3264. let nt = new nullTools();
  3265. nt.define(win, 'adBlock', false);
  3266. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3267. }
  3268. };
  3269.  
  3270. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3271.  
  3272. scripts['newdeaf-online.net'] = {
  3273. dom: () => {
  3274. let adNodes = _document.querySelectorAll('.ads');
  3275. if (!adNodes)
  3276. return;
  3277. let getter = x => {
  3278. let val = x;
  3279. return () => (_console.warn('read .ads', name, val), val);
  3280. };
  3281. let setter = x => _console.warn('skip write .ads', name, x);
  3282. for (let adNode of adNodes)
  3283. for (let name of ['innerHTML'])
  3284. Object.defineProperty(adNode, name, {
  3285. get: getter(ads[name]),
  3286. set: setter
  3287. });
  3288. }
  3289. };
  3290.  
  3291. scripts['overclockers.ru'] = {
  3292. dom: () => scriptLander(() => {
  3293. let killed = () => _console.warn('Anti-Adblock killed.');
  3294. if ('$' in win)
  3295. win.$ = new Proxy($, {
  3296. apply: (tgt, that, args) => {
  3297. let res = tgt.apply(that, args);
  3298. if (res[0] && res[0] === _document.body) {
  3299. res.html = killed;
  3300. res.empty = killed;
  3301. }
  3302. return res;
  3303. }
  3304. });
  3305. })
  3306. };
  3307. scripts['forums.overclockers.ru'] = {
  3308. now: () => {
  3309. createStyle('.needblock {position: fixed; left: -10000px}');
  3310. Object.defineProperty(win, 'adblck', {
  3311. get: () => 'no',
  3312. set: () => undefined,
  3313. enumerable: true
  3314. });
  3315. }
  3316. };
  3317.  
  3318. scripts['pb.wtf'] = {
  3319. other: ['piratbit.org', 'piratbit.ru'],
  3320. dom: () => {
  3321. // line above topic content and images in the slider in the header
  3322. let remove = node => (_console.log('removed', node), node.parentNode.removeChild(node));
  3323. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3324. if (location.hostname === el.hostname &&
  3325. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3326. remove(el.closest('div, tr'));
  3327. continue;
  3328. }
  3329. // ads in the topic header in case filter above wasn't enough
  3330. let parent = el.closest('tr');
  3331. if (parent) {
  3332. let span = (parent.querySelector('span') || {}).textContent;
  3333. span && span.startsWith('YO!') && remove(parent);
  3334. }
  3335. }
  3336. // casino ad button in random places
  3337. for (let el of _document.querySelectorAll('.btn-group')) {
  3338. el = el.parentNode;
  3339. if (el.tagName === 'CENTER')
  3340. remove(el.parentNode);
  3341. }
  3342. // ads in comments
  3343. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3344. if (el && el.parentNode.children[2] == el)
  3345. remove(el);
  3346. }
  3347. };
  3348.  
  3349. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3350.  
  3351. scripts['peka2.tv'] = () => {
  3352. let bodyClass = 'body--branding';
  3353. let checkNode = node => {
  3354. for (let className of node.classList)
  3355. if (className.includes('banner') || className === bodyClass) {
  3356. _removeAttribute(node, 'style');
  3357. node.classList.remove(className);
  3358. for (let attr of Array.from(node.attributes))
  3359. if (attr.name.startsWith('advert'))
  3360. _removeAttribute(node, attr.name);
  3361. }
  3362. };
  3363. (new MutationObserver(ms => {
  3364. let m, node;
  3365. for (m of ms) for (node of m.addedNodes)
  3366. if (node instanceof HTMLElement)
  3367. checkNode(node);
  3368. })).observe(_de, {childList: true, subtree: true});
  3369. (new MutationObserver(ms => {
  3370. for (let m of ms)
  3371. checkNode(m.target);
  3372. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3373. };
  3374.  
  3375. scripts['qrz.ru'] = {
  3376. now: () => {
  3377. let nt = new nullTools();
  3378. nt.define(win, 'ab', false);
  3379. nt.define(win, 'tryMessage', nt.func(null));
  3380. }
  3381. };
  3382.  
  3383. scripts['razlozhi.ru'] = {
  3384. now: () => {
  3385. for (let func of ['createShadowRoot', 'attachShadow'])
  3386. if (func in _Element)
  3387. _Element[func] = function(){
  3388. return this.cloneNode();
  3389. };
  3390. }
  3391. };
  3392.  
  3393. scripts['rbc.ru'] = {
  3394. other: ['autonews.ru', 'rbcplus.ru', 'sportrbc.ru'],
  3395. now: () => {
  3396. selectiveCookies('adb_on');
  3397. let _RA = void 0;
  3398. let setArgs = {
  3399. 'showBanners': true,
  3400. 'showAds': true,
  3401. 'banners.staticPath': '',
  3402. 'paywall.staticPath': '',
  3403. 'banners.dfp.config': [],
  3404. 'banners.dfp.pageTargeting': () => null,
  3405. };
  3406. Object.defineProperty(win, 'RA', {
  3407. get: () => _RA,
  3408. set: vl => {
  3409. _console.log('RA =', vl);
  3410. if ('repo' in vl) {
  3411. _console.log('RA.repo =', vl.repo);
  3412. vl.repo = new Proxy(vl.repo, {
  3413. set: (o, name, val) => {
  3414. if (name === 'banner') {
  3415. _console.log(`RA.repo.${name} =`, val);
  3416. val = new Proxy(val, {
  3417. get: (o, name) => {
  3418. let res = o[name];
  3419. if (typeof o[name] === 'function') {
  3420. res = () => null;
  3421. res.toString = o[name].toString.bind(o[name]);
  3422. }
  3423. if (name === 'isInited')
  3424. res = true;
  3425. _console.warn(`get RA.repo.banner.${name}`, res);
  3426. return res;
  3427. }
  3428. });
  3429. }
  3430. o[name] = val;
  3431. return true;
  3432. }
  3433. });
  3434. } else
  3435. _console.log('Unable to locate RA.repo');
  3436. _RA = new Proxy(vl, {
  3437. set: (o, name, val) => {
  3438. if (name === 'config') {
  3439. _console.log('RA.config =', val);
  3440. if ('set' in val) {
  3441. val.set = new Proxy(val.set, {
  3442. apply: (set, that, args) => {
  3443. let name = args[0];
  3444. if (name in setArgs)
  3445. args[1] = setArgs[name];
  3446. if (name in setArgs || name === 'checkad')
  3447. _console.log('RA.config.set(', ...args, ')');
  3448. return Reflect.apply(set, that, args);
  3449. }
  3450. });
  3451. val.set('showAds', true); // pretend ads already were shown
  3452. }
  3453. }
  3454. o[name] = val;
  3455. return true;
  3456. }
  3457. });
  3458. }
  3459. });
  3460. Object.defineProperty(win, 'bannersConfig', {
  3461. get: () => [], set: () => null
  3462. });
  3463. // pretend there is a paywall landing on screen already
  3464. let pwl = _document.createElement('div');
  3465. pwl.style.display = 'none';
  3466. pwl.className = 'js-paywall-landing';
  3467. _document.documentElement.appendChild(pwl);
  3468. // detect and skip execution of one of the ABP detectors
  3469. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3470. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3471. win.setTimeout = function setTimeout() {
  3472. if (typeof arguments[0] === 'function') {
  3473. let fts = _toString(arguments[0]);
  3474. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  3475. _console.log('Skipped setTimout(', fts, arguments[1], ')');
  3476. return;
  3477. }
  3478. }
  3479. return _setTimeout(this, arguments);
  3480. };
  3481. // hide banner placeholders
  3482. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  3483. },
  3484. dom: () => {
  3485. // hide sticky banner place at the top of the page
  3486. for (let itm of _document.querySelectorAll('.l-sticky'))
  3487. if (itm.querySelector('.banner__container__link'))
  3488. itm.style.display = 'none';
  3489. }
  3490. };
  3491.  
  3492. scripts['rp5.ru'] = {
  3493. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3494. now: () => {
  3495. Object.defineProperty(win, 'sContentBottom', {
  3496. get: () => '',
  3497. set: () => true
  3498. });
  3499. },
  3500. dom: () => {
  3501. let node = selectNodeByTextContent('Разместить текстовое объявление', { root: _de.querySelector('#content-wrapper'), shallow: true });
  3502. if (node)
  3503. node.style.display = 'none';
  3504. }
  3505. };
  3506.  
  3507. scripts['rutube.ru'] = () => scriptLander(() => {
  3508. let _parse = JSON.parse;
  3509. let _skip_enabled = false;
  3510. JSON.parse = (...args) => {
  3511. let res = _parse(...args),
  3512. log = false;
  3513. if (!res)
  3514. return res;
  3515. // parse player configuration
  3516. if ('appearance' in res || 'video_balancer' in res) {
  3517. log = true;
  3518. if (res.appearance) {
  3519. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3520. res.appearance.forbid_seek = false;
  3521. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3522. res.appearance.forbid_timeline_preview = false;
  3523. }
  3524. _skip_enabled = !!res.remove_unseekable_blocks;
  3525. //res.advert = [];
  3526. delete res.advert;
  3527. //for (let limit of res.limits)
  3528. // limit.limit = 0;
  3529. delete res.limits;
  3530. //res.yast = null;
  3531. //res.yast_live_online = null;
  3532. delete res.yast;
  3533. delete res.yast_live_online;
  3534. Object.defineProperty(res, 'stat', {
  3535. get: () => [],
  3536. set: () => true,
  3537. enumerable: true
  3538. });
  3539. }
  3540.  
  3541. // parse video configuration
  3542. if ('video_url' in res) {
  3543. log = true;
  3544. if (res.cuepoints && !_skip_enabled)
  3545. for (let point of res.cuepoints) {
  3546. point.is_pause = false;
  3547. point.show_navigation = true;
  3548. point.forbid_seek = false;
  3549. }
  3550. }
  3551.  
  3552. if (log)
  3553. _console.log('[rutube]', res);
  3554. return res;
  3555. };
  3556. });
  3557.  
  3558. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3559. let _addEventListener = _Document.addEventListener;
  3560. _document.addEventListener = function(event, callback) {
  3561. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3562. return;
  3563. return _addEventListener.apply(this, arguments);
  3564. };
  3565. });
  3566.  
  3567. scripts['smotret-anime.ru'] = () => scriptLander(() => {
  3568. deepWrapAPI(root => {
  3569. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3570. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3571. let stopper = e => _pause(e.target);
  3572. root.Audio = new Proxy(root.Audio, {
  3573. construct: (audio, args) => {
  3574. let res = new audio(...args);
  3575. _addEventListener(res, 'play', stopper, true);
  3576. return res;
  3577. }
  3578. });
  3579. _createElement = root.Document.prototype.createElement;
  3580. root.Document.prototype.createElement = function createElement() {
  3581. let res = _createElement.apply(this, arguments);
  3582. if (res instanceof HTMLAudioElement)
  3583. _addEventListener(res, 'play', stopper, true);
  3584. return res;
  3585. };
  3586. });
  3587. }, deepWrapAPI);
  3588.  
  3589. scripts['spaces.ru'] = () => {
  3590. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3591. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3592. };
  3593.  
  3594. scripts['spam-club.blogspot.co.uk'] = () => {
  3595. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  3596. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  3597. let wrapGetter = (getter) => {
  3598. let _getter = getter;
  3599. return function() {
  3600. let _size = _getter.apply(this, arguments);
  3601. return _size ? _size : 1;
  3602. };
  3603. };
  3604. _clientHeight.get = wrapGetter(_clientHeight.get);
  3605. _clientWidth.get = wrapGetter(_clientWidth.get);
  3606. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3607. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  3608. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3609. _set_onload = _onload.set;
  3610. _onload.set = function() {
  3611. if (this instanceof HTMLImageElement)
  3612. return true;
  3613. _set_onload.apply(this, arguments);
  3614. };
  3615. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3616. };
  3617.  
  3618. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3619.  
  3620. scripts['sports.ru'] = {
  3621. now: () => {
  3622. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3623. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3624. // extra functionality: shows/hides panel at the top depending on scroll direction
  3625. createStyle([
  3626. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3627. '.user-panel-up { top: -40px!important }'
  3628. ], {id: 'userPanelSlide'}, false);
  3629. },
  3630. dom: () => {
  3631. (function lookForPanel() {
  3632. let panel = _document.querySelector('.user-panel__fixed');
  3633. if (!panel)
  3634. setTimeout(lookForPanel, 100);
  3635. else
  3636. window.addEventListener(
  3637. 'wheel', function(e) {
  3638. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3639. panel.classList.add('user-panel-up');
  3640. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3641. panel.classList.remove('user-panel-up');
  3642. }, false
  3643. );
  3644. })();
  3645. }
  3646. };
  3647.  
  3648. scripts['stealthz.ru'] = {
  3649. dom: () => {
  3650. // skip timeout
  3651. let $ = _document.querySelector.bind(_document);
  3652. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3653. if (!timer_1 || !timer_2)
  3654. return;
  3655. timer_1.style.display = 'none';
  3656. timer_2.style.display = 'block';
  3657. }
  3658. };
  3659.  
  3660. scripts['xittv.net'] = () => scriptLander(() => {
  3661. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  3662. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  3663. let _jwplayer = void 0;
  3664. Object.defineProperty(win, 'jwplayer', {
  3665. get: () => _jwplayer,
  3666. set: x => {
  3667. _jwplayer = new Proxy(x, {
  3668. apply: (fun, that, args) => {
  3669. let res = fun.apply(that, args);
  3670. res = new Proxy(res, {
  3671. get: (obj, name) => {
  3672. if (logNames.includes(name) && obj[name] instanceof Function)
  3673. return new Proxy(obj[name], {
  3674. apply: (fun, that, args) => {
  3675. if (name === 'setup') {
  3676. let o = args[0];
  3677. if (o)
  3678. delete o.advertising;
  3679. }
  3680. if (name === 'on' || name === 'trigger') {
  3681. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  3682. if (events.length === 1 && skipEvents.includes(events[0]))
  3683. return res;
  3684. if (events.length > 1) {
  3685. let names = [];
  3686. for (let event of events)
  3687. if (!skipEvents.includes(event))
  3688. names.push(event);
  3689. if (names.length > 0)
  3690. args[0] = names.join(" ");
  3691. else
  3692. return res;
  3693. }
  3694. }
  3695. let subres = fun.apply(that, args);
  3696. _console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  3697. return subres;
  3698. }
  3699. });
  3700. return obj[name];
  3701. }
  3702. });
  3703. return res;
  3704. }
  3705. });
  3706. _console.log('jwplayer =', x);
  3707. }
  3708. });
  3709. });
  3710.  
  3711. scripts['yap.ru'] = {
  3712. other: ['yaplakal.com'],
  3713. now: () => {
  3714. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3715. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3716. }
  3717. };
  3718.  
  3719. scripts['rambler.ru'] = {
  3720. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  3721. now: () => {
  3722. selectiveCookies('detect_count');
  3723. scriptLander(() => {
  3724. // Prevent autoplay
  3725. if (!('EaglePlayer' in win)) {
  3726. let _EaglePlayer = void 0;
  3727. Object.defineProperty(win, 'EaglePlayer', {
  3728. enumerable: true,
  3729. get: () => _EaglePlayer,
  3730. set: x => {
  3731. if (x === _EaglePlayer)
  3732. return true;
  3733. _EaglePlayer = new Proxy(x, {
  3734. construct: (targ, args) => {
  3735. let player = new targ(...args);
  3736. if (!player.options) {
  3737. _console.log('EaglePlayer: no options', EaglePlayer);
  3738. return player;
  3739. }
  3740. Object.defineProperty(player.options, 'autoplay', {
  3741. get: () => false,
  3742. set: () => true
  3743. });
  3744. Object.defineProperty(player.options, 'scroll', {
  3745. get: () => false,
  3746. set: () => true
  3747. });
  3748. return player;
  3749. }
  3750. });
  3751. }
  3752. });
  3753. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3754. let isAutoplay = /^autoplay$/i;
  3755. _Element.setAttribute = function setAttribute(name) {
  3756. if (!this._stopped && isAutoplay.test(name)) {
  3757. _console.log('Prevented assigning autoplay attribute.');
  3758. return null;
  3759. }
  3760. return _setAttribute(this, arguments);
  3761. };
  3762. } else {
  3763. _console.log('EaglePlayer function already exists.');
  3764. if (inIFrame) {
  3765. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3766. let isAutoplay = /^autoplay$/i;
  3767. _Element.setAttribute = function setAttribute(name) {
  3768. if (!this._stopped && isAutoplay.test(name)) {
  3769. _console.log('Prevented assigning autoplay attribute.');
  3770. this._stopped = true;
  3771. this.play = () => {
  3772. _console.log('Prevented attempt to force-start playback.');
  3773. delete this.play;
  3774. };
  3775. return null;
  3776. }
  3777. return _setAttribute(this, arguments);
  3778. };
  3779. }
  3780. }
  3781. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3782. return;
  3783. let nt = new nullTools();
  3784. // Adblock Detector
  3785. let _hidden = void 0;
  3786. Object.defineProperty(win, 'QW50aS1BZEJsb2Nr', {
  3787. set: vl => {
  3788. for (let name in vl) delete vl[name];
  3789. nt.define(vl, 'Detector', nt.proxy({
  3790. getBlockingStatus: () => new Promise(),
  3791. blockingDetectors: [],
  3792. baitURLPrefix: '',
  3793. commonRules: []
  3794. }));
  3795. nt.define(vl, 'isAdBlockFlag', '');
  3796. nt.define(vl, 'ruid', '');
  3797. nt.define(vl, 'user', nt.proxy({
  3798. getOrSetUid: () => null
  3799. }));
  3800. _console.log('Found Adblock Detector.');
  3801. _hidden = vl;
  3802. },
  3803. get: () => _hidden
  3804. });
  3805. // prevent ads from loading
  3806. let blockObfuscated = false;
  3807. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  3808. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3809. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3810. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3811. let _cssText_get = _cssText.get;
  3812. _cssText.configurable = false;
  3813. _cssText.get = function() {
  3814. let cssText = _cssText_get.call(this);
  3815. if (cssText.includes('content:')) {
  3816. _console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3817. blockObfuscated = true;
  3818. return null;
  3819. }
  3820. return cssText;
  3821. };
  3822. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3823. let _setTimeout = win.setTimeout;
  3824. win.setTimeout = function(f) {
  3825. if (blockObfuscated && obfuscation.test(_toString(f))) {
  3826. _console.warn('Stopped setTimeout for:', _toString(f).slice(0,100), '\u2026');
  3827. return null;
  3828. };
  3829. return _setTimeout.apply(this, arguments);
  3830. };
  3831. // fake global Adf object
  3832. let Adf_banner = {};
  3833. [
  3834. 'reloadssp', 'sspScroll',
  3835. 'sspRich', 'ssp'
  3836. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3837. nt.define(win, 'Adf', nt.proxy({
  3838. banner: nt.proxy(Adf_banner)
  3839. }));
  3840. // extra script to remove partner news on gazeta.ru
  3841. if (!location.hostname.includes('gazeta.ru'))
  3842. return;
  3843. (new MutationObserver(
  3844. (ms) => {
  3845. let m, node, header;
  3846. for (m of ms) for (node of m.addedNodes)
  3847. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3848. header = node.querySelector('.sausage-header');
  3849. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3850. node.style.display = 'none';
  3851. }
  3852. }
  3853. )).observe(_document.documentElement, { childList:true, subtree: true });
  3854. }, `let inIFrame = ${inIFrame}`, nullTools)
  3855. }
  3856. };
  3857.  
  3858. scripts['reactor.cc'] = {
  3859. other: ['joyreactor.cc', 'pornreactor.cc'],
  3860. now: () => {
  3861. selectiveEval();
  3862. scriptLander(() => {
  3863. let nt = new nullTools();
  3864. win.open = function(){
  3865. throw new Error('Redirect prevention.');
  3866. };
  3867. nt.define(win, 'Worker', function(){});
  3868. nt.define(win, 'JRCH', win.CoinHive);
  3869. }, nullTools);
  3870. },
  3871. click: function(e) {
  3872. let node = e.target;
  3873. if (node.nodeType === _Node.ELEMENT_NODE &&
  3874. node.style.position === 'absolute' &&
  3875. node.style.zIndex > 0)
  3876. node.parentNode.removeChild(node);
  3877. },
  3878. dom: function() {
  3879. let tid = void 0;
  3880. function probe() {
  3881. let node = selectNodeByTextContent('блокировщик рекламы');
  3882. if (!node) return;
  3883. while (node.parentNode.offsetHeight < 750 && node !== _document.body)
  3884. node = node.parentNode;
  3885. _setAttribute(node, 'style', 'background:none!important');
  3886. // stop observer
  3887. if (!tid) tid = setTimeout(() => this.disconnect(), 1000);
  3888. }
  3889. (new MutationObserver(probe))
  3890. .observe(_document, { childList:true, subtree:true });
  3891. }
  3892. };
  3893.  
  3894. scripts['auto.ru'] = () => {
  3895. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3896. let userAdsListAds = (
  3897. '.listing-list > .listing-item,'+
  3898. '.listing-item_type_fixed.listing-item'
  3899. );
  3900. let catalogAds = (
  3901. 'div[class*="layout_catalog-inline"],'+
  3902. 'div[class$="layout_horizontal"]'
  3903. );
  3904. let otherAds = (
  3905. '.advt_auto,'+
  3906. '.sidebar-block,'+
  3907. '.pager-listing + div[class],'+
  3908. '.card > div[class][style],'+
  3909. '.sidebar > div[class],'+
  3910. '.main-page__section + div[class],'+
  3911. '.listing > tbody'
  3912. );
  3913. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3914. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3915. gardener(otherAds, words);
  3916. };
  3917.  
  3918. scripts['rsload.net'] = {
  3919. load: () => {
  3920. let dis = _document.querySelector('label[class*="cb-disable"]');
  3921. if (dis)
  3922. dis.click();
  3923. },
  3924. click: e => {
  3925. let t = e.target;
  3926. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3927. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3928. }
  3929. };
  3930.  
  3931. let domain;
  3932. // add alternative domain names if present and wrap functions into objects
  3933. for (let name in scripts) {
  3934. if (scripts[name] instanceof Function)
  3935. scripts[name] = { now: scripts[name] };
  3936. for (domain of (scripts[name].other||[])) {
  3937. if (domain in scripts)
  3938. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3939. scripts[domain] = scripts[name];
  3940. }
  3941. delete scripts[name].other;
  3942. }
  3943. // look for current domain in the list and run appropriate code
  3944. domain = _document.domain;
  3945. while (domain.includes('.')) {
  3946. if (domain in scripts) for (let when in scripts[domain])
  3947. switch(when) {
  3948. case 'now':
  3949. scripts[domain][when]();
  3950. break;
  3951. case 'dom':
  3952. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3953. break;
  3954. default:
  3955. _document.addEventListener (when, scripts[domain][when], false);
  3956. }
  3957. domain = domain.slice(domain.indexOf('.') + 1);
  3958. }
  3959.  
  3960. // Batch script lander
  3961. if (!skipLander)
  3962. landScript(batchLand, batchPrepend);
  3963.  
  3964. { // JS Fixes Tools Menu
  3965. let openOptions = function() {
  3966. let ovl = _createElement('div'),
  3967. inner = _createElement('div');
  3968. ovl.style = (
  3969. 'position: fixed;'+
  3970. 'top:0; left:0;'+
  3971. 'bottom: 0; right: 0;'+
  3972. 'background: rgba(0,0,0,0.85);'+
  3973. 'z-index: 2147483647;'+
  3974. 'padding: 5em'
  3975. );
  3976. inner.style = (
  3977. 'background: whitesmoke;'+
  3978. 'font-size: 10pt;'+
  3979. 'color: black;'+
  3980. 'padding: 1em'
  3981. );
  3982. inner.textContent = 'JS Fixes Tools';
  3983. inner.appendChild(_createElement('br'));
  3984. inner.appendChild(_createElement('br'));
  3985. ovl.addEventListener(
  3986. 'click', function(e) {
  3987. if (e.target === ovl) {
  3988. ovl.parentNode.removeChild(ovl);
  3989. e.preventDefault();
  3990. }
  3991. e.stopPropagation();
  3992. }, false
  3993. );
  3994.  
  3995. let sObjBtn = _createElement('button');
  3996. sObjBtn.onclick = getStrangeObjectsList;
  3997. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  3998. inner.appendChild(_createElement('br'));
  3999. inner.appendChild(sObjBtn);
  4000.  
  4001. _document.body.appendChild(ovl);
  4002. ovl.appendChild(inner);
  4003. };
  4004.  
  4005. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  4006. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  4007. _document.addEventListener(
  4008. 'keydown', function(e) {
  4009. if ((e.code === opKey[opPos] || e.location) &&
  4010. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  4011. opPos += e.location ? 0 : 1;
  4012. e.stopPropagation();
  4013. e.preventDefault();
  4014. } else
  4015. opPos = 0;
  4016. if (opPos === opKey.length) {
  4017. opPos = 0;
  4018. openOptions();
  4019. }
  4020. }, false
  4021. );
  4022. }
  4023. })();