RU AdList JS Fixes

try to take over the world!

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

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