RU AdList JS Fixes

try to take over the world!

当前为 2018-11-09 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20181109.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 _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  1368. _get_contentWindow = Function.prototype.apply.bind(_contentWindow.get);
  1369. _contentWindow.get = function() {
  1370. wrapAPI(this);
  1371. return _get_contentWindow(this);;
  1372. };
  1373. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  1374.  
  1375. // wrap API on contentDocument access
  1376. let _contentDocument = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentDocument');
  1377. let _get_contentDocument = Function.prototype.apply.bind(_contentDocument.get);
  1378. _contentDocument.get = function() {
  1379. wrapAPI(this);
  1380. return _get_contentDocument(this);
  1381. };
  1382. Object.defineProperty(HTMLIFrameElement.prototype, 'contentDocument', _contentDocument);
  1383.  
  1384. // manual children objects traverser to avoid issues
  1385. // with calling querySelectorAll on wrong types of objects
  1386. let empty = [];
  1387. let wrapFrames = root => {
  1388. if (root instanceof HTMLIFrameElement) {
  1389. wrapAPI(root);
  1390. return;
  1391. }
  1392. for (let child of (root.children || empty))
  1393. wrapFrames(child);
  1394. };
  1395.  
  1396. // wrap API in a newly appended iframe objects
  1397. let _appendChild = Function.prototype.apply.bind(Node.prototype.appendChild);
  1398. Node.prototype.appendChild = function () {
  1399. let res = _appendChild(this, arguments);
  1400. wrapFrames(res);
  1401. return res;
  1402. };
  1403.  
  1404. // wrap API in iframe objects created with innerHTML of element on page
  1405. let _innerHTML = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML');
  1406. let _set_innerHTML = Function.prototype.apply.bind(_innerHTML.set);
  1407. _innerHTML.set = function() {
  1408. _set_innerHTML(this, arguments);
  1409. if (_document.contains(this))
  1410. wrapFrames(this);
  1411. };
  1412. Object.defineProperty(_Element.prototype, 'innerHTML', _innerHTML);
  1413.  
  1414. wrapAPI(win);
  1415. }
  1416.  
  1417. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1418. scriptLander(
  1419. () => {
  1420. // onerror callback blacklist
  1421. let masks = [],
  1422. blockAll = /(^|\.)(((a-dot-)?kinozal-tv|rutracker-org)\.appspot\.com)$/,
  1423. isBlocked = url => masks.some(mask => mask.test(url)) || blockAll.test(location.hostname);
  1424. for (let filter of [// blacklist
  1425. '/fuckadblock/', '/fuckadblock.',
  1426. '||185.87.50.147^',
  1427. '||10root25.website^', '||24video.xxx^',
  1428. '||adlabs.ru^', '||adspayformymortgage.win^', '||amgload.net^', '||aviabay.ru^',
  1429. '||bgrndi.com^', '||brokeloy.com^',
  1430. '||cnamerutor.ru^',
  1431. '||directadvert.ru^', '||dsn-fishki.ru^', '||docfilms.info^', '||dreadfula.ru^',
  1432. '||et-code.ru^', '||etcodes.com^',
  1433. '||franecki.net^', '||film-doma.ru^',
  1434. '||free-torrent.org^', '||free-torrent.pw^',
  1435. '||free-torrents.org^', '||free-torrents.pw^',
  1436. '||game-torrent.info^', '||gocdn.ru^',
  1437. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1438. '||joyreactor.cc^', '||pornreactor.cc^', '||reactor.cc^',
  1439. '||kiev.ua^', '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1440. '||klcheck.com^', '||kuveres.com^',
  1441. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1442. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1443. '||nickhel.com^',
  1444. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1445. '||piguiqproxy.com^', '||pkpojhc.com^',
  1446. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1447. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1448. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1449. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1450. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||ttarget.ru^',
  1451. '||utarget.ru^',
  1452. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1453. '||xxuhter.ru^',
  1454. '||yuiout.online^',
  1455. '||zmctrack.net^', '||zoom-film.ru^'])
  1456. masks.push(new RegExp(
  1457. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1458. .replace(/\*/g, '.*?')
  1459. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  1460. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  1461. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^/.]+\\.)*?'),
  1462. 'i'));
  1463. // main script
  1464. deepWrapAPI(root => {
  1465. let _call = root.Function.prototype.call,
  1466. _defineProperty = root.Object.defineProperty,
  1467. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor;
  1468. onerror: {
  1469. // 'onerror' handler for scripts from blacklisted sources
  1470. let scriptMap = new WeakMap();
  1471. let _Reflect_apply = root.Reflect.apply,
  1472. _HTMLScriptElement = root.HTMLScriptElement,
  1473. _HTMLImageElement = root.HTMLImageElement;
  1474. let _get_tagName = _call.bind(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1475. _get_scr_src = _call.bind(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1476. _get_img_src = _call.bind(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1477. let _get_src = node => {
  1478. if (node instanceof _HTMLScriptElement)
  1479. return _get_scr_src(node);
  1480. if (node instanceof _HTMLImageElement)
  1481. return _get_img_src(node);
  1482. return void 0
  1483. };
  1484. let _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1485. _set_onerror = _call.bind(_onerror.set);
  1486. _onerror.get = function() {
  1487. return scriptMap.get(this) || null;
  1488. };
  1489. _onerror.set = function(callback) {
  1490. if (typeof callback !== 'function') {
  1491. scriptMap.delete(this);
  1492. _set_onerror(this, callback);
  1493. return;
  1494. }
  1495. scriptMap.set(this, callback);
  1496. _set_onerror(this, function() {
  1497. let src = _get_src(this);
  1498. if (isBlocked(src)) {
  1499. console.warn(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1500. return;
  1501. }
  1502. _Reflect_apply(scriptMap.get(this), this, arguments);
  1503. });
  1504. };
  1505. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1506. }
  1507. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1508. WSWrap: { // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1509. if (true /*/Maxthon/.test(navigator.appVersion) ||
  1510. 'InstallTrigger' in win && 'StopIteration' in win*/) {
  1511. let _ws = _getOwnPropertyDescriptor(root, 'WebSocket');
  1512. if (!_ws)
  1513. break WSWrap;
  1514. _ws.value = new Proxy(_ws.value, {
  1515. construct: (ws, args) => {
  1516. if (isBlocked(args[0])) {
  1517. console.log('Blocked WS connection:', args[0]);
  1518. return {};
  1519. }
  1520. return new ws(...args);
  1521. }
  1522. });
  1523. _defineProperty(root, 'WebSocket', _ws);
  1524. }
  1525. }
  1526. untrustedClick: {
  1527. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1528. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1529. let _dispatchEvent = _call.bind(root.EventTarget.prototype.dispatchEvent);
  1530. root.EventTarget.prototype.dispatchEvent = function dispatchEvent(e) {
  1531. if (!e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1532. !this.parentNode && this.tagName === 'A' && this.target[0] === '_') {
  1533. console.log('Blocked dispatching a click event on a parentless anchor:', this);
  1534. return;
  1535. }
  1536. return _dispatchEvent(this, ...arguments);
  1537. };
  1538. }
  1539. // XHR Wrapper
  1540. let _proto = void 0;
  1541. try {
  1542. _proto = root.XMLHttpRequest.prototype;
  1543. } catch(ignore) {
  1544. return;
  1545. };
  1546. // blacklist of domains where all third-party requests are ignored
  1547. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1548. // highly suspicious URLs
  1549. let suspicious = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1550. let on_get_ban = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+)$/i;
  1551. let on_post_ban = /^https?:\/\/(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1552. let yandex_direct = /^https?:\/\/(yandex(\.[a-z]{2,3}){1,2}\/(images\/[a-z0-9/_-]{40,}|j?clck\/.*)|[^.]+\.yandex\.net\/static\/main\.js(\?.*)?)$/i;
  1553.  
  1554. function checkRequest(fname, method, url) {
  1555. if (isBlocked(url) ||
  1556. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1557. method === 'GET' && on_get_ban.test(url) ||
  1558. method === 'POST' && on_post_ban.test(url) ||
  1559. yandex_direct.test(url)) {
  1560. console.log(`Blocked ${fname} ${method} request:`, url);
  1561. return true;
  1562. }
  1563. if (suspicious.test(url))
  1564. console.warn(`Suspicious ${fname} ${method} request:`, url);
  1565. return false;
  1566. }
  1567.  
  1568. let xhrStopList = new WeakSet();
  1569. let _open = root.Function.prototype.apply.bind(_proto.open);
  1570. _proto.open = function open() {
  1571. '[native code]';
  1572. if (checkRequest('xhr', ...arguments)) {
  1573. xhrStopList.add(this);
  1574. return;
  1575. }
  1576. return _open(this, arguments);
  1577. };
  1578. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1579. name => {
  1580. let func = _proto[name];
  1581. _proto[name] = function(...args) {
  1582. return xhrStopList.has(this) ? null : func.apply(this, args);
  1583. };
  1584. }
  1585. );
  1586.  
  1587. let _fetch = root.Function.prototype.apply.bind(root.fetch);
  1588. root.fetch = function fetch() {
  1589. '[native code]';
  1590. let url = arguments[0];
  1591. let method = arguments[1] ? arguments[1].method : void 0;
  1592. if (arguments[0] instanceof Request) {
  1593. method = url.method;
  1594. url = url.url;
  1595. }
  1596. if (checkRequest('fetch', method, url))
  1597. return new Promise(() => null);
  1598. return _fetch(root, arguments);
  1599. };
  1600. });
  1601.  
  1602. win.stop = () => {
  1603. console.warn('window.stop() ...y tho?');
  1604. for (let sheet of _document.styleSheets)
  1605. if (sheet.disabled) {
  1606. sheet.disabled = false;
  1607. console.log('Re-enabled:', sheet);
  1608. }
  1609. }
  1610. }, deepWrapAPI
  1611. );
  1612.  
  1613. // === Helper functions ===
  1614.  
  1615. // function to search and remove nodes by content
  1616. // selector - standard CSS selector to define set of nodes to check
  1617. // words - regular expression to check content of the suspicious nodes
  1618. // params - object with multiple extra parameters:
  1619. // .log - display log in the console
  1620. // .hide - set display to none instead of removing from the page
  1621. // .parent - parent node to remove if content is found in the child node
  1622. // .siblings - number of simling nodes to remove (excluding text nodes)
  1623. let scRemove = (node) => node.parentNode.removeChild(node);
  1624. let scHide = function(node) {
  1625. let style = _getAttribute(node, 'style') || '',
  1626. hide = ';display:none!important;';
  1627. if (style.indexOf(hide) < 0)
  1628. _setAttribute(node, 'style', style + hide);
  1629. };
  1630.  
  1631. function scissors (selector, words, scope, params) {
  1632. let logger = (...args) => { if (params.log) console.log(...args) };
  1633. if (!scope.contains(_document.body))
  1634. logger('[s] scope', scope);
  1635. let remFunc = (params.hide ? scHide : scRemove),
  1636. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1637. toRemove = [],
  1638. siblings;
  1639. for (let node of scope.querySelectorAll(selector)) {
  1640. // drill up to a parent node if specified, break if not found
  1641. if (params.parent) {
  1642. let old = node;
  1643. node = node.closest(params.parent);
  1644. if (node === null || node.contains(scope)) {
  1645. logger('[s] went out of scope with', old);
  1646. continue;
  1647. }
  1648. }
  1649. logger('[s] processing', node);
  1650. if (toRemove.includes(node))
  1651. continue;
  1652. if (words.test(node.innerHTML)) {
  1653. // skip node if already marked for removal
  1654. logger('[s] marked for removal');
  1655. toRemove.push(node);
  1656. // add multiple nodes if defined more than one sibling
  1657. siblings = Math.abs(params.siblings) || 0;
  1658. while (siblings) {
  1659. node = node[iterFunc];
  1660. if (!node) break; // can't go any further - exit
  1661. logger('[s] adding sibling node', node);
  1662. toRemove.push(node);
  1663. siblings -= 1;
  1664. }
  1665. }
  1666. }
  1667. let toSkip = [];
  1668. for (let node of toRemove)
  1669. if (!toRemove.every(other => other === node || !node.contains(other)))
  1670. toSkip.push(node);
  1671. if (toRemove.length)
  1672. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1673. for (let node of toRemove) if (!toSkip.includes(node))
  1674. remFunc(node);
  1675. }
  1676.  
  1677. // function to perform multiple checks if ads inserted with a delay
  1678. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1679. // also does 1 extra check when a page completely loads
  1680. // selector and words - passed dow to scissors
  1681. // params - object with multiple extra parameters:
  1682. // .log - display log in the console
  1683. // .root - selector to narrow down scope to scan;
  1684. // .observe - if true then check will be performed continuously;
  1685. // Other parameters passed down to scissors.
  1686. function gardener(selector, words, params) {
  1687. let logger = (...args) => { if (params.log) console.log(...args) };
  1688. params = params || {};
  1689. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1690. let scope;
  1691. let globalScope = [_de];
  1692. let domLoaded = false;
  1693. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1694. let onevent = e => {
  1695. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1696. for (let node of scope)
  1697. scissors(selector, words, node, params);
  1698. };
  1699. let repeater = n => {
  1700. if (!domLoaded && n) {
  1701. setTimeout(repeater, 500, n - 1);
  1702. scope = getScope(params.root);
  1703. if (!scope) // exit if the root element is not present on the page
  1704. return 0;
  1705. onevent({type: 'Repeater'});
  1706. }
  1707. };
  1708. repeater(20);
  1709. _document.addEventListener(
  1710. 'DOMContentLoaded', (e) => {
  1711. domLoaded = true;
  1712. // narrow down scope to a specific element
  1713. scope = getScope(params.root);
  1714. if (!scope) // exit if the root element is not present on the page
  1715. return 0;
  1716. logger('[g] scope', scope);
  1717. // add observe mode if required
  1718. if (params.observe) {
  1719. let params = { childList:true, subtree: true };
  1720. let observer = new MutationObserver(
  1721. function(ms) {
  1722. for (let m of ms)
  1723. if (m.addedNodes.length)
  1724. onevent(m);
  1725. }
  1726. );
  1727. for (let node of scope)
  1728. observer.observe(node, params);
  1729. logger('[g] observer enabled');
  1730. }
  1731. onevent(e);
  1732. }, false);
  1733. // wait for a full page load to do one extra cut
  1734. win.addEventListener('load', onevent, false);
  1735. }
  1736.  
  1737. // wrap popular methods to open a new tab to catch specific behaviours
  1738. function createWindowOpenWrapper(openFunc) {
  1739. let _createElement = _Document.prototype.createElement,
  1740. _appendChild = _Element.prototype.appendChild,
  1741. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1742.  
  1743. let nt = new nullTools();
  1744. fakeNative(openFunc);
  1745.  
  1746. let parser = _createElement.call(_document, 'a');
  1747. let openWhitelist = (url, parent) => {
  1748. parser.href = url;
  1749. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1750. parent.hostname === 'radikal.ru' && url === void 0;
  1751. };
  1752.  
  1753. let redefineOpen = (root) => {
  1754. if ('open' in root) {
  1755. let _open = root.open.bind(root);
  1756. nt.define(root, 'open', (...args) => {
  1757. if (openWhitelist(args[0], location)) {
  1758. console.log('Whitelisted popup:', ...args);
  1759. return _open(...args);
  1760. }
  1761. return openFunc(...args);
  1762. });
  1763. }
  1764. };
  1765. redefineOpen(win);
  1766.  
  1767. function createElement() {
  1768. '[native code]';
  1769. let el = _createElement.apply(this, arguments);
  1770. // redefine window.open in first-party frames
  1771. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1772. el.addEventListener('load', (e) => {
  1773. try {
  1774. redefineOpen(e.target.contentWindow);
  1775. } catch(ignore) {}
  1776. }, false);
  1777. return el;
  1778. }
  1779. fakeNative(createElement);
  1780.  
  1781. let redefineCreateElement = (obj) => {
  1782. for (let root of [obj.document, _Document.prototype]) if ('createElement' in root)
  1783. nt.define(root, 'createElement', createElement);
  1784. };
  1785. redefineCreateElement(win);
  1786.  
  1787. // wrap window.open in newly added first-party frames
  1788. _Element.prototype.appendChild = function appendChild() {
  1789. '[native code]';
  1790. let el = _appendChild.apply(this, arguments);
  1791. if (el instanceof HTMLIFrameElement)
  1792. try {
  1793. redefineOpen(el.contentWindow);
  1794. redefineCreateElement(el.contentWindow);
  1795. } catch(ignore) {}
  1796. return el;
  1797. };
  1798. fakeNative(_Element.prototype.appendChild);
  1799. }
  1800.  
  1801. // Function to catch and block various methods to open a new window with 3rd-party content.
  1802. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1803. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1804. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1805. // node or simply a link with piece of javascript code in the HREF attribute.
  1806. function preventPopups() {
  1807. // call sandbox-me if in iframe and not whitelisted
  1808. if (inIFrame) {
  1809. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1810. return;
  1811. }
  1812.  
  1813. scriptLander(() => {
  1814. let nt = new nullTools({log:true});
  1815. let open = (...args) => {
  1816. '[native code]';
  1817. console.warn('Site attempted to open a new window', ...args);
  1818. return {
  1819. document: nt.proxy({
  1820. write: nt.func({}, 'write'),
  1821. writeln: nt.func({}, 'writeln')
  1822. }),
  1823. location: nt.proxy({})
  1824. };
  1825. };
  1826.  
  1827. createWindowOpenWrapper(open);
  1828.  
  1829. console.log('Popup prevention enabled.');
  1830. }, nullTools, createWindowOpenWrapper);
  1831. }
  1832.  
  1833. // Helper function to close background tab if site opens itself in a new tab and then
  1834. // loads a 3rd-party page in the background one (thus performing background redirect).
  1835. function preventPopunders() {
  1836. // create "close_me" event to call high-level window.close()
  1837. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1838. let callClose = () => {
  1839. console.log('close call');
  1840. window.close();
  1841. };
  1842. window.addEventListener(eventName, callClose, true);
  1843.  
  1844. scriptLander(() => {
  1845. // get host of a provided URL with help of an anchor object
  1846. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1847. let parseURL = _document.createElement('A');
  1848. let getHost = url => {
  1849. parseURL.href = url;
  1850. return parseURL.hostname
  1851. };
  1852. // site went to a new tab and attempts to unload
  1853. // call for high-level close through event
  1854. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1855. // check is URL local or goes to different site
  1856. let isLocal = (url) => {
  1857. if (url === location.pathname || url === location.href)
  1858. return true; // URL points to current pathname or full address
  1859. let host = getHost(url);
  1860. let site = location.hostname;
  1861. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1862. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1863. };
  1864.  
  1865. let _open = window.open.bind(window);
  1866. let open = (...args) => {
  1867. '[native code]';
  1868. let url = args[0];
  1869. if (url && isLocal(url))
  1870. window.addEventListener('beforeunload', closeWindow, true);
  1871. return _open(...args);
  1872. };
  1873.  
  1874. createWindowOpenWrapper(open);
  1875.  
  1876. console.log("Background redirect prevention enabled.");
  1877. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1878. }
  1879.  
  1880. // Mix between check for popups and popunders
  1881. // Significantly more agressive than both and can't be used as universal solution
  1882. function preventPopMix() {
  1883. if (inIFrame) {
  1884. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  1885. return;
  1886. }
  1887.  
  1888. // create "close_me" event to call high-level window.close()
  1889. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1890. let callClose = () => {
  1891. console.log('close call');
  1892. window.close();
  1893. };
  1894. window.addEventListener(eventName, callClose, true);
  1895.  
  1896. scriptLander(() => {
  1897. let _open = window.open,
  1898. parseURL = _document.createElement('A');
  1899. // get host of a provided URL with help of an anchor object
  1900. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1901. let getHost = (url) => {
  1902. parseURL.href = url;
  1903. return parseURL.host;
  1904. };
  1905. // site went to a new tab and attempts to unload
  1906. // call for high-level close through event
  1907. let closeWindow = () => {
  1908. _open(window.location,'_self');
  1909. window.dispatchEvent(new CustomEvent(eventName, {}));
  1910. };
  1911. // check is URL local or goes to different site
  1912. function isLocal(url) {
  1913. let loc = window.location;
  1914. if (url === loc.pathname || url === loc.href)
  1915. return true; // URL points to current pathname or full address
  1916. let host = getHost(url),
  1917. site = loc.host;
  1918. if (host === '')
  1919. return false; // URLs with unusual protocol may have empty 'host'
  1920. if (host.length > site.length)
  1921. [site, host] = [host, site];
  1922. return site.includes(host, site.length - host.length);
  1923. }
  1924.  
  1925. // add check for redirect for 5 seconds, then disable it
  1926. function checkRedirect() {
  1927. window.addEventListener('beforeunload', closeWindow, true);
  1928. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1929. }
  1930.  
  1931. function open(url, name) {
  1932. '[native code]';
  1933. if (url && isLocal(url) && (!name || name === '_blank')) {
  1934. console.warn('Suspicious local new window', arguments);
  1935. checkRedirect();
  1936. return _open.apply(this, arguments);
  1937. }
  1938. console.warn('Blocked attempt to open a new window', arguments);
  1939. return {
  1940. document: {
  1941. write: () => {},
  1942. writeln: () => {}
  1943. }
  1944. };
  1945. }
  1946.  
  1947. function clickHandler(e) {
  1948. let link = e.target,
  1949. url = link.href||'';
  1950. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1951. console.log('Link', link, 'were created dinamically, but looks fine.');
  1952. return true;
  1953. }
  1954. if (isLocal(url) && link.target === '_blank') {
  1955. console.log('Suspicious local link', link);
  1956. checkRedirect();
  1957. return;
  1958. }
  1959. console.log('Blocked suspicious click on a link', link);
  1960. e.stopPropagation();
  1961. e.preventDefault();
  1962. }
  1963.  
  1964. createWindowOpenWrapper(open, clickHandler);
  1965.  
  1966. console.log("Mixed popups prevention enabled.");
  1967. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  1968. }
  1969. // External listener for case when site known to open popups were loaded in iframe
  1970. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1971. // Some sites replace frame's window.location with data-url to run in clean context
  1972. if (!inIFrame) window.addEventListener(
  1973. 'message', function(e) {
  1974. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1975. return;
  1976. let src = e.data.href;
  1977. for (let frame of _document.querySelectorAll('iframe'))
  1978. if (frame.contentWindow === e.source) {
  1979. if (frame.hasAttribute('sandbox')) {
  1980. if (!frame.sandbox.contains('allow-popups'))
  1981. return; // exit frame since it's already sandboxed and popups are blocked
  1982. // remove allow-popups if frame already sandboxed
  1983. frame.sandbox.remove('allow-popups');
  1984. } else
  1985. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1986. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1987. // but to apply content must be reloaded and this script will re-apply it in the result
  1988. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1989. console.log('Disallowed popups from iframe', frame);
  1990.  
  1991. // reload frame content to apply restrictions
  1992. if (!src) {
  1993. src = frame.src;
  1994. console.log('Unable to get current iframe location, reloading from src', src);
  1995. } else
  1996. console.log('Reloading iframe with URL', src);
  1997. frame.src = 'about:blank';
  1998. frame.src = src;
  1999. }
  2000. }, false
  2001. );
  2002.  
  2003. function selectiveEval(extra) {
  2004. scriptLander(() => {
  2005. let _eval_def = Object.getOwnPropertyDescriptor(win, 'eval');
  2006. if (!_eval_def || !_eval_def.value) {
  2007. console.log('Unable to wrap window.eval.', _eval_def);
  2008. return;
  2009. }
  2010. let genericPatterns = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  2011. let _eval_val = _eval_def.value;
  2012. _eval_def.value = function(...args) {
  2013. if (genericPatterns.test(args[0]) || extra && extra.test(args[0])) {
  2014. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2015. return null;
  2016. }
  2017. return _eval_val.apply(this, args);
  2018. };
  2019. Object.defineProperty(win, 'eval', _eval_def);
  2020. }, `let extra = ${extra}`);
  2021. }
  2022.  
  2023. // hides cookies by pattern and attempts to remove them if they already set
  2024. // also prevents setting new versions of such cookies
  2025. function selectiveCookies(scPattern, scPaths = []) {
  2026. scriptLander(() => {
  2027. let ga = '_g(at?|id)|__utm[a-z]'; // Google Analytics Cookies
  2028. scPattern = new RegExp(`(^|;\\s?)(${scPattern}|${ga})($|=)`);
  2029. if (isFirefox && scPaths.length)
  2030. scPaths.forEach((path, id) => scPaths[id] = `${path}/`);
  2031. scPaths.push('/');
  2032. let _doc_proto = ('cookie' in _Document.prototype) ? _Document.prototype : Object.getPrototypeOf(_document);
  2033. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2034. if (_cookie) {
  2035. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2036. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2037. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2038. let expireAge = '-99999999';
  2039. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2040. let expireAttempted = {};
  2041. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2042. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2043. let expire = (cookie, that) => {
  2044. let domain = that.location.hostname.split('.'),
  2045. name = cookie.replace(/=.*/,'');
  2046. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2047. while (domain.length > 1) {
  2048. try {
  2049. scPaths.forEach(
  2050. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2051. );
  2052. } catch(e) { console.warn(e); }
  2053. domain.shift();
  2054. }
  2055. expireAttempted[name] = true;
  2056. console.log('Removing existing cookie:', cookie);
  2057. };
  2058. // skip setting unwanted cookies
  2059. _cookie.set = function(value) {
  2060. if (scPattern.test(value)) {
  2061. console.warn('Ignored cookie:', value);
  2062. // try to remove same cookie if it already exists using exact values from the set string
  2063. if (scPattern.test(_get_cookie(this))) {
  2064. let parts = value.split(/;\s?/),
  2065. name = parts[0].replace(/=.*/,''),
  2066. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2067. skip = [name, 'expires', 'Max-Age'];
  2068. for (let part of parts)
  2069. if (!skip.includes(part.replace(/=.*/,'')))
  2070. newParts.push(part);
  2071. try {
  2072. _set_cookie(this, newParts.join(';'));
  2073. } catch(e) { console.warn(e); }
  2074. console.log('Removing existing cookie:', name);
  2075. }
  2076. return;
  2077. }
  2078. return _set_cookie(this, value);
  2079. };
  2080. // hide unwanted cookies from site
  2081. _cookie.get = function() {
  2082. let res = _get_cookie(this);
  2083. if (scPattern.test(res)) {
  2084. let stack = [];
  2085. for (let cookie of res.split(/;\s?/))
  2086. if (!scPattern.test(cookie))
  2087. stack.push(cookie);
  2088. else {
  2089. let name = cookie.replace(/=.*/,'');
  2090. if (expireAttempted[name]) {
  2091. console.log('Unable to expire:', cookie);
  2092. expireAttempted[name] = false;
  2093. }
  2094. if (!(name in expireAttempted))
  2095. expire(cookie, this);
  2096. }
  2097. res = stack.join('; ');
  2098. }
  2099. return res;
  2100. };
  2101. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2102. }
  2103. console.log('Active cookies:', document.cookie);
  2104. }, `let scPattern = "${scPattern}", scPaths = ${scPaths}, isFirefox = ${isFirefox};`);
  2105. }
  2106.  
  2107. /*{ // simple toString wrapper, might be useful to prevent detection
  2108. '[native code]';
  2109. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2110. let baseText = Function.prototype.toString.toString();
  2111. let protect = new WeakSet();
  2112. protect.add(_Document.prototype.createElement);
  2113. protect.add(_Node.prototype.appendChild);
  2114. protect.add(_Node.prototype.removeChild);
  2115. win.Function.prototype.toString = function() {
  2116. if (protect.has(this))
  2117. return baseText.replace('toString', this.name);
  2118. return _toString(this);
  2119. };
  2120. protect.add(Function.prototype.toString);
  2121. }*/
  2122.  
  2123. // === Scripts for specific domains ===
  2124.  
  2125. let scripts = {};
  2126. // prevent popups and redirects block
  2127. // Popups
  2128. scripts.preventPopups = {
  2129. other: [
  2130. 'biqle.ru',
  2131. 'chaturbate.com',
  2132. 'dfiles.ru',
  2133. 'eporner.eu',
  2134. 'hentaiz.org',
  2135. 'mirrorcreator.com',
  2136. 'online-multy.ru',
  2137. 'radikal.ru', 'rumedia.ws',
  2138. 'tapehub.tech', 'thepiratebay.org',
  2139. 'unionpeer.com',
  2140. 'zippyshare.com'
  2141. ],
  2142. now: preventPopups
  2143. };
  2144. // Popunders (background redirect)
  2145. scripts.preventPopunders = {
  2146. other: [
  2147. 'lostfilm-online.ru',
  2148. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2149. 'perfectgirls.net'
  2150. ],
  2151. now: preventPopunders
  2152. };
  2153. // PopMix (both types of popups encountered on site)
  2154. scripts['openload.co'] = {
  2155. other: ['oload.tv', 'oload.info'],
  2156. now: () => {
  2157. let nt = new nullTools();
  2158. nt.define(win, 'CNight', win.CoinHive);
  2159. if (location.pathname.startsWith('/embed/')) {
  2160. nt.define(win, 'BetterJsPop', {
  2161. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2162. config: ((o) => console.warn('BetterJsPop.config', o)),
  2163. Browser: { isChrome: true }
  2164. });
  2165. nt.define(win, 'isSandboxed', nt.func(null));
  2166. nt.define(win, 'adblock', false);
  2167. nt.define(win, 'adblock2', false);
  2168. } else preventPopMix();
  2169. }
  2170. };
  2171. scripts['turbobit.net'] = preventPopMix;
  2172.  
  2173. scripts['tapochek.net'] = () => {
  2174. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2175. let _appendChild = Object.getOwnPropertyDescriptor(_Node.prototype, 'appendChild');
  2176. let _appendChild_value = _appendChild.value;
  2177. _appendChild.value = function appendChild(node) {
  2178. if (this === _document.body)
  2179. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2180. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2181. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2182. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2183. throw '...eenope!';
  2184. return _appendChild_value.apply(this, arguments);
  2185. };
  2186. Object.defineProperty(_Node.prototype, 'appendChild', _appendChild);
  2187.  
  2188. // disable window focus tricks and changing location
  2189. let focusHandlerName = /\WfocusAchieved\(/
  2190. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2191. let _setInterval = win.setInterval;
  2192. win.setInterval = (...args) => {
  2193. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2194. console.log('skip setInterval for', ...args);
  2195. return -1;
  2196. }
  2197. return _setInterval(...args);
  2198. };
  2199. let _addEventListener = win.addEventListener;
  2200. win.addEventListener = function(...args) {
  2201. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2202. console.log('skip addEventListener for', ...args);
  2203. return void 0;
  2204. }
  2205. return _addEventListener.apply(this, args);
  2206. };
  2207.  
  2208. // generic popup prevention
  2209. preventPopups();
  2210. };
  2211.  
  2212. scripts['rustorka.com'] = {
  2213. other: ['rustorka.club', 'rustorka.lib', 'rustorka.net'],
  2214. now: () => {
  2215. selectiveEval(/antiadblock/);
  2216. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2217. scriptLander(() => {
  2218. // wrap window.open to catch a popup if it triggers
  2219. win.open = (...args) => {
  2220. console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2221. location.replace(location.href);
  2222. return null;
  2223. };
  2224. window.addEventListener('DOMContentLoaded', () => {
  2225. let link = void 0;
  2226. _document.body.addEventListener('mousedown', e => {
  2227. link = e.target.closest('a, select, #fancybox-title-wrap');
  2228. }, false);
  2229. let _open = window.open.bind(window);
  2230. let _getAttribute = Function.prototype.call.bind(_Element.prototype.getAttribute);
  2231. win.open = (...args) => {
  2232. let url = args[0];
  2233. if (link instanceof HTMLAnchorElement) {
  2234. // third-party post links
  2235. let href = _getAttribute(link, 'href');
  2236. if (link.classList.contains('postLink') &&
  2237. !link.matches(`a[href*="${location.hostname}"]`) &&
  2238. (href === url || link.href === url))
  2239. return _open(...args);
  2240. // onclick # links
  2241. if (href === '#' && /window\.open/.test(_getAttribute(link, 'onclick')))
  2242. return _open(...args);
  2243. // force local links to load in the current window
  2244. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2245. location.assign(href);
  2246. }
  2247. // list of image hostings under upload picture button (new comment)
  2248. if (link instanceof HTMLSelectElement &&
  2249. !url.includes(location.hostname) &&
  2250. link.value === url)
  2251. return _open(...args);
  2252. // open screenshot in a new window
  2253. if (link instanceof HTMLSpanElement &&
  2254. link.id === 'fancybox-title-wrap')
  2255. return _open(...args);
  2256. // looks like tabunder
  2257. if (link === null && url === location.href)
  2258. location.replace(url); // reload current page
  2259. // other cases
  2260. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2261. return {};
  2262. };
  2263. }, true);
  2264. }, nullTools)
  2265. }
  2266. };
  2267.  
  2268. // = other ======================================================================================
  2269. scripts['1tv.ru'] = {
  2270. other: ['mediavitrina.ru'],
  2271. now: () => scriptLander(() => {
  2272. let nt = new nullTools();
  2273. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2274. let disablePlugins = {
  2275. 'antiblock': false,
  2276. 'stat1tv': false
  2277. };
  2278. let _EUMPConfig = void 0;
  2279. let _EUMPConfig_set = x => {
  2280. if (x.plugins) {
  2281. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2282. console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2283. }
  2284. _EUMPConfig = x;
  2285. };
  2286. if ('EUMPConfig' in win)
  2287. _EUMPConfig_set(win.EUMPConfig);
  2288. Object.defineProperty(win, 'EUMPConfig', {
  2289. enumerable: true,
  2290. get: () => _EUMPConfig,
  2291. set: _EUMPConfig_set
  2292. });
  2293. }, nullTools)
  2294. };
  2295.  
  2296. scripts['2picsun.ru'] = {
  2297. other: [
  2298. 'pics2sun.ru', '3pics-img.ru'
  2299. ],
  2300. now: () => {
  2301. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2302. }
  2303. };
  2304.  
  2305. scripts['4pda.ru'] = {
  2306. now: () => {
  2307. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2308. let isForum = location.pathname.startsWith('/forum/'),
  2309. remove = node => (node && node.parentNode.removeChild(node)),
  2310. hide = node => (node && (node.style.display = 'none'));
  2311.  
  2312. // save links to non-overridden functions to use later
  2313. let protectedElems;
  2314. // protect/hide changed attributes in case site attempt to restore them
  2315. function styleProtector(eventMode) {
  2316. let _toLowerCase = String.prototype.toLowerCase,
  2317. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2318. protectedElems = new WeakMap();
  2319. function protoOverride(element, functionName, isStyleCheck, returnIfProtected) {
  2320. let originalFunction = element.prototype[functionName];
  2321. element.prototype[functionName] = function wrapper() {
  2322. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2323. return returnIfProtected(this, arguments);
  2324. return originalFunction.apply(this, arguments);
  2325. };
  2326. }
  2327. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2328. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2329. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2330. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2331. if (!eventMode)
  2332. return protectedElems;
  2333. let e = _document.createEvent('Event');
  2334. e.initEvent('protoOverride', false, false);
  2335. window.protectedElems = protectedElems;
  2336. window.dispatchEvent(e);
  2337. }
  2338. if (!isFirefox)
  2339. protectedElems = styleProtector(false);
  2340. else {
  2341. let script = _document.createElement('script');
  2342. script.textContent = `(${styleProtector.toString()})(true);`;
  2343. window.addEventListener(
  2344. 'protoOverride', function protoOverrideCallback() {
  2345. if (win.protectedElems) {
  2346. protectedElems = win.protectedElems;
  2347. delete win.protectedElems;
  2348. }
  2349. _document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2350. }, true
  2351. );
  2352. _appendChild(script);
  2353. _removeChild(script);
  2354. }
  2355.  
  2356. // clean a page
  2357. window.addEventListener(
  2358. 'DOMContentLoaded', function() {
  2359. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2360. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2361.  
  2362. HeaderAds: {
  2363. // hide ads above HEADER
  2364. let header = _document.querySelector('.drop-search');
  2365. if (!header) {
  2366. console.warn('Unable to locate header element');
  2367. break HeaderAds;
  2368. }
  2369. header = header.parentNode.parentNode;
  2370. for (let itm of header.parentNode.children)
  2371. if (itm !== header)
  2372. hide(itm);
  2373. else break;
  2374. }
  2375.  
  2376. if (isForum) {
  2377. let itm = _document.querySelector('#logostrip');
  2378. if (itm)
  2379. remove(itm.parentNode.nextSibling);
  2380. // clear background in the download frame
  2381. if (location.pathname.startsWith('/forum/dl/')) {
  2382. let setBackground = node => _setAttribute(
  2383. node,
  2384. 'style', (_getAttribute(node, 'style') || '') +
  2385. ';background-color:#4ebaf6!important'
  2386. );
  2387. setBackground(_document.body);
  2388. for (let itm of _document.querySelectorAll('body > div'))
  2389. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2390. remove(itm);
  2391. else
  2392. setBackground(itm);
  2393. }
  2394. // exist from DOMContentLoaded since the rest is not for forum
  2395. return;
  2396. }
  2397.  
  2398. FixNavMenu: {
  2399. // restore DevDB link in the navigation
  2400. let itm = _document.querySelector('#nav li a[href$="/devdb/"]')
  2401. if (!itm) {
  2402. console.warn('Unable to locate navigation menu');
  2403. break FixNavMenu;
  2404. }
  2405. itm.closest('li').style.display = 'block';
  2406. // hide ad link from the navigation
  2407. hide(_document.querySelector('#nav li a[data-dotrack]'));
  2408. }
  2409. SidebarAds: {
  2410. // remove ads from sidebar
  2411. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child');
  2412. if (!aside.length) {
  2413. console.warn('Unable to locate sidebar');
  2414. break SidebarAds;
  2415. }
  2416. let post;
  2417. for (let side of aside) {
  2418. console.log('Processing potential sidebar:', side);
  2419. for (let itm of Array.from(side.children)) {
  2420. post = itm.classList.contains('post');
  2421. if (itm.querySelector('iframe') && !post)
  2422. remove(itm);
  2423. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2424. hide(itm);
  2425. }
  2426. }
  2427. }
  2428.  
  2429. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2430.  
  2431. let extra = 'background-image:none!important;background-color:transparent!important',
  2432. fakeStyles = new WeakMap(),
  2433. styleProxy = {
  2434. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2435. set: function(target, prop, value) {
  2436. let fakeStyle = fakeStyles.get(target);
  2437. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2438. return true;
  2439. }
  2440. };
  2441. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2442. if (!(itm.offsetWidth > 0.95 * width() &&
  2443. itm.offsetHeight > 0.85 * height()))
  2444. continue;
  2445. if (itm.tagName !== 'A') {
  2446. fakeStyles.set(itm.style, {
  2447. 'backgroundImage': itm.style.backgroundImage,
  2448. 'backgroundColor': itm.style.backgroundColor
  2449. });
  2450.  
  2451. try {
  2452. Object.defineProperty(itm, 'style', {
  2453. value: new Proxy(itm.style, styleProxy),
  2454. enumerable: true
  2455. });
  2456. } catch (e) {
  2457. console.log('Unable to protect style property.', e);
  2458. }
  2459.  
  2460. if (protectedElems)
  2461. protectedElems.set(itm, _getAttribute(itm, 'style'));
  2462.  
  2463. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2464. }
  2465. if (itm.tagName === 'A') {
  2466. if (protectedElems)
  2467. protectedElems.set(itm, _getAttribute(itm, 'style'));
  2468. _setAttribute(itm, 'style', 'display:none!important');
  2469. }
  2470. }
  2471. }
  2472. );
  2473. }
  2474. };
  2475.  
  2476. scripts['adhands.ru'] = () => scriptLander(() => {
  2477. let nt = new nullTools();
  2478. try {
  2479. let _adv;
  2480. Object.defineProperty(win, 'adv', {
  2481. get: () => _adv,
  2482. set: (v) => {
  2483. console.log('Blocked advert on adhands.ru.');
  2484. nt.define(v, 'advert', '');
  2485. _adv = v;
  2486. }
  2487. });
  2488. } catch (ignore) {
  2489. if (!win.adv)
  2490. console.log('Unable to locate advert on adhands.ru.');
  2491. else {
  2492. console.log('Blocked advert on adhands.ru.');
  2493. nt.define(win.adv, 'advert', '');
  2494. }
  2495. }
  2496. }, nullTools);
  2497.  
  2498. scripts['all-episodes.tv'] = () => {
  2499. let nt = new nullTools();
  2500. nt.define(win, 'perX1', 2);
  2501. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2502. };
  2503.  
  2504. scripts['allhentai.ru'] = () => {
  2505. selectiveEval();
  2506. preventPopups();
  2507. scriptLander(() => {
  2508. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2509. if (!_onerror)
  2510. return;
  2511. _onerror.set = (...args) => console.log(args[0].toString());
  2512. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2513. });
  2514. };
  2515.  
  2516. scripts['allmovie.pro'] = {
  2517. other: ['rufilmtv.org'],
  2518. dom: function() {
  2519. // pretend to be Android to make site use different played for ads
  2520. if (isSafari)
  2521. return;
  2522. Object.defineProperty(navigator, 'userAgent', {
  2523. get: function(){
  2524. 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';
  2525. },
  2526. enumerable: true
  2527. });
  2528. }
  2529. };
  2530.  
  2531. scripts['anidub-online.ru'] = {
  2532. other: ['anime.anidub.com', 'online.anidub.com'],
  2533. dom: function() {
  2534. if (win.ogonekstart1)
  2535. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2536. },
  2537. now: () => createStyle([
  2538. '.background {background: none!important;}',
  2539. '.background > script + div,'+
  2540. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2541. '{display:none!important}'
  2542. ])
  2543. };
  2544.  
  2545. scripts['avito.ru'] = () => selectiveCookies('abp|bltsr|cmtchd|crookie|is_adblock');
  2546.  
  2547. scripts['di.fm'] = () => scriptLander(() => {
  2548. let log = false;
  2549. // wrap global app object to catch registration of specific modules
  2550. let _di = void 0;
  2551. Object.defineProperty(win, 'di', {
  2552. get: () => _di,
  2553. set: vl => {
  2554. if (vl === _di)
  2555. return;
  2556. log && console.log('di =', vl);
  2557. _di = new Proxy(vl, {
  2558. set: (di, name, vl) => {
  2559. if (vl === di[name])
  2560. return true;
  2561. if (name === 'app') {
  2562. log && console.log('di.app =', vl);
  2563. if ('module' in vl)
  2564. vl.module = new Proxy(vl.module, {
  2565. apply: (module, that, args) => {
  2566. if (/Wall|Banner|Detect/.test(args[0])) {
  2567. let name = args[0];
  2568. log && console.warn('wrap', name, 'module');
  2569. if (typeof args[1] === 'function')
  2570. args[1] = new Proxy(args[1], {
  2571. apply: (fun, that, args) => {
  2572. if (args[0]) // module object
  2573. args[0].start = () => console.log('Skipped start of', name);
  2574. return Reflect.apply(fun, that, args);
  2575. }
  2576. });
  2577. }
  2578. return Reflect.apply(module, that, args);
  2579. }
  2580. });
  2581. }
  2582. di[name] = vl;
  2583. return true;
  2584. }
  2585. });
  2586. }
  2587. });
  2588. // don't send errorception logs
  2589. Object.defineProperty(win, 'onerror', {
  2590. set: vl => log && console.warn('Skipped global onerror callback', vl)
  2591. });
  2592. });
  2593.  
  2594. scripts['drive2.ru'] = () => {
  2595. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2596. scriptLander(() => {
  2597. let _d2 = void 0;
  2598. Object.defineProperty(win, 'd2', {
  2599. get: () => _d2,
  2600. set: o => {
  2601. if (o === _d2)
  2602. return true;
  2603. _d2 = new Proxy(o, {
  2604. set: (tgt, prop, val) => {
  2605. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2606. val = () => null;
  2607. tgt[prop] = val;
  2608. return true;
  2609. }
  2610. });
  2611. }
  2612. });
  2613. });
  2614. };
  2615.  
  2616. scripts['fastpic.ru'] = () => {
  2617. let nt = new nullTools();
  2618. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2619. nt.define(win, `_0x${'4955'}`, []);
  2620. };
  2621.  
  2622. scripts['fishki.net'] = () => {
  2623. scriptLander(() => {
  2624. let nt = new nullTools();
  2625. let fishki = {};
  2626. nt.define(fishki, 'adv', nt.proxy({
  2627. afterAdblockCheck: nt.func(null),
  2628. refreshFloat: nt.func(null)
  2629. }));
  2630. nt.define(fishki, 'is_adblock', false);
  2631. nt.define(win, 'fishki', fishki);
  2632. }, nullTools);
  2633. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2634. };
  2635.  
  2636. scripts['friends.in.ua'] = () => scriptLander(() => {
  2637. Object.defineProperty(win, 'need_warning', {
  2638. get: () => 0, set: () => null
  2639. });
  2640. });
  2641.  
  2642. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2643.  
  2644. scripts['hdgo.cc'] = {
  2645. other: ['46.30.43.38', 'couber.be'],
  2646. now: () => (new MutationObserver(
  2647. (ms) => {
  2648. let m, node;
  2649. for (m of ms) for (node of m.addedNodes)
  2650. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2651. node.removeAttribute('onerror');
  2652. }
  2653. )).observe(_document.documentElement, { childList:true, subtree: true })
  2654. };
  2655.  
  2656. scripts['gismeteo.ru'] = {
  2657. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2658. now: () => {
  2659. selectiveCookies('ab_[^=]*|bltsr|redirect|_gab');
  2660. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2661. }
  2662. };
  2663.  
  2664. scripts['hdrezka.ag'] = () => {
  2665. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2666. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2667. };
  2668.  
  2669. scripts['hqq.tv'] = () => scriptLander(() => {
  2670. // disable anti-debugging in hqq.tv player
  2671. 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);
  2672. deepWrapAPI(root => {
  2673. // skip obfuscated stuff and a few other calls
  2674. let _setInterval = root.setInterval,
  2675. _setTimeout = root.setTimeout,
  2676. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2677. root.setInterval = (...args) => {
  2678. let fun = args[0];
  2679. if (fun instanceof Function) {
  2680. let text = _toString(fun),
  2681. skip = text.includes('check();') || isObfuscated(text);
  2682. console.warn('setInterval', text, 'skip', skip);
  2683. if (skip) return -1;
  2684. }
  2685. return _setInterval.apply(this, args);
  2686. };
  2687. let wrappedST = new WeakSet();
  2688. root.setTimeout = (...args) => {
  2689. let fun = args[0];
  2690. if (fun instanceof Function) {
  2691. let text = _toString(fun),
  2692. skip = fun.name === 'check' || isObfuscated(text);
  2693. if (!wrappedST.has(fun)) {
  2694. console.warn('setTimeout', text, 'skip', skip);
  2695. wrappedST.add(fun);
  2696. }
  2697. if (skip) return;
  2698. }
  2699. return _setTimeout.apply(this, args);
  2700. };
  2701. // skip 'debugger' call
  2702. let _eval = root.eval;
  2703. root.eval = text => {
  2704. if (typeof text === 'string' && text.includes('debugger;')) {
  2705. console.warn('skip eval', text);
  2706. return;
  2707. }
  2708. _eval(text);
  2709. };
  2710. // Prevent RegExpt + toString trick
  2711. let _proto = void 0;
  2712. try {
  2713. _proto = root.RegExp.prototype;
  2714. } catch(ignore) {
  2715. return;
  2716. }
  2717. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  2718. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  2719. Object.defineProperty(_proto, 'toString', {
  2720. enumerable: _RE_tS.enumerable,
  2721. configurable: _RE_tS.configurable,
  2722. get: () => _RE_tSV,
  2723. set: val => console.warn('Attempt to change toString for', this, 'with', _toString(val))
  2724. });
  2725. });
  2726. }, deepWrapAPI);
  2727.  
  2728. scripts['hideip.me'] = {
  2729. now: () => scriptLander(() => {
  2730. let _innerHTML = Object.getOwnPropertyDescriptor(_Element.prototype, 'innerHTML');
  2731. let _set_innerHTML = _innerHTML.set;
  2732. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2733. let _get_innerText = _innerText.get;
  2734. let div = _document.createElement('div');
  2735. _innerHTML.set = function(...args) {
  2736. _set_innerHTML.call(div, args[0].replace('i','a'));
  2737. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2738. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2739. console.log('Anti-Adblock killed.');
  2740. return true;
  2741. }
  2742. _set_innerHTML.apply(this, args);
  2743. };
  2744. Object.defineProperty(_Element.prototype, 'innerHTML', _innerHTML);
  2745. Object.defineProperty(win, 'adblock', {
  2746. get: () => false,
  2747. set: () => null,
  2748. enumerable: true
  2749. });
  2750. let _$ = {};
  2751. let _$_map = new WeakMap();
  2752. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2753. let _val_gOPD = _gOPD.value;
  2754. _gOPD.value = function(...args) {
  2755. let _res = _val_gOPD.apply(this, args);
  2756. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2757. delete _res.get;
  2758. delete _res.set;
  2759. _res.value = win[args[1]];
  2760. }
  2761. return _res;
  2762. };
  2763. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2764. let getJQWrap = (n) => {
  2765. let name = n;
  2766. return {
  2767. enumerable: true,
  2768. get: () => _$[name],
  2769. set: x => {
  2770. if (_$_map.has(x)) {
  2771. _$[name] = _$_map.get(x);
  2772. return true;
  2773. }
  2774. if (x === _$.$ || x === _$.jQuery) {
  2775. _$[name] = x;
  2776. return true;
  2777. }
  2778. _$[name] = new Proxy(x, {
  2779. apply: (t, o, args) => {
  2780. let _res = t.apply(o, args);
  2781. if (_$_map.has(_res.is))
  2782. _res.is = _$_map.get(_res.is);
  2783. else {
  2784. let _is = _res.is;
  2785. _res.is = function(...args) {
  2786. if (args[0] === ':hidden')
  2787. return false;
  2788. return _is.apply(this, args);
  2789. };
  2790. _$_map.set(_is, _res.is);
  2791. }
  2792. return _res;
  2793. }
  2794. });
  2795. _$_map.set(x, _$[name]);
  2796. return true;
  2797. }
  2798. };
  2799. };
  2800. Object.defineProperty(win, '$', getJQWrap('$'));
  2801. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2802. let _dP = Object.defineProperty;
  2803. Object.defineProperty = function(...args) {
  2804. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2805. return void 0;
  2806. return _dP.apply(this, args);
  2807. };
  2808. })
  2809. };
  2810.  
  2811. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2812. let nt = new nullTools();
  2813. /*jslint evil: true */ // yes, evil, I know
  2814. let _write = _document.write.bind(_document);
  2815. /*jslint evil: false */
  2816. nt.define(_document, 'write', t => {
  2817. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2818. if (id && id[1])
  2819. return _write(`<div id="${id[1]}"></div>${t}`);
  2820. return _write('');
  2821. });
  2822. });
  2823.  
  2824. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  2825.  
  2826. scripts['ivi.ru'] = () => {
  2827. let _xhr_open = win.XMLHttpRequest.prototype.open;
  2828. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  2829. if (typeof url === 'string')
  2830. if (url.endsWith('/track'))
  2831. return;
  2832. return _xhr_open.call(this, method, url, ...args);
  2833. };
  2834. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  2835. let _responseText_get = _responseText.get;
  2836. _responseText.get = function() {
  2837. if (this.__responseText__)
  2838. return this.__responseText__;
  2839. let res = _responseText_get.apply(this, arguments);
  2840. let o;
  2841. try {
  2842. if (res)
  2843. o = JSON.parse(res);
  2844. } catch(ignore) {};
  2845. let changed = false;
  2846. if (o && o.result) {
  2847. if (o.result instanceof Array &&
  2848. 'adv_network_logo_url' in o.result[0]) {
  2849. o.result = [];
  2850. changed = true;
  2851. }
  2852. if (o.result.show_adv) {
  2853. o.result.show_adv = false;
  2854. changed = true;
  2855. }
  2856. }
  2857. if (changed) {
  2858. console.log('changed response >>', o);
  2859. res = JSON.stringify(o);
  2860. }
  2861. this.__responseText__ = res;
  2862. return res;
  2863. };
  2864. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  2865. };
  2866.  
  2867. scripts['kinopoisk.ru'] = () => {
  2868. selectiveCookies('bltsr|cmtchd|crookie|kpunk');
  2869. // set no-branding body style and adjust other blocks on the page
  2870. createStyle([
  2871. 'body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }',
  2872. '#top { height: 150px !important }',
  2873. '#top_superscreen { display: none !important }',
  2874. '#top_3banners { display: block !important }'
  2875. ]);
  2876. // catch branding and other things
  2877. let _KP = void 0;
  2878. Object.defineProperty(win, 'KP', {
  2879. get: () => _KP,
  2880. set: val => {
  2881. if (_KP === val)
  2882. return true;
  2883. _KP = new Proxy(val, {
  2884. set: (kp, name, val) => {
  2885. if (name === 'branding')
  2886. return true;
  2887. if (name === 'config')
  2888. val = new Proxy(val, {
  2889. set: (cfg, name, val) => {
  2890. if (name === 'anContextUrl')
  2891. return true;
  2892. if (name === 'adfoxEnabled' || name === 'hasBranding')
  2893. val = false;
  2894. if (name === 'adfoxVideoAdUrls')
  2895. val = {flash:{}, html:{}};
  2896. cfg[name] = val;
  2897. return true;
  2898. }
  2899. });
  2900. kp[name] = val;
  2901. return true;
  2902. }
  2903. });
  2904. console.log('KP =', val);
  2905. }
  2906. });
  2907. };
  2908.  
  2909. scripts['kinozal-tv.appspot.com'] = {
  2910. other: ['a-dot-kinozal-tv.appspot.com'],
  2911. now: () => {
  2912. // They check if 'startsWith' in String.prototype
  2913. // and skip parts of ABP detector if it's not there
  2914. delete String.prototype.startsWith;
  2915. }
  2916. };
  2917.  
  2918. scripts['korrespondent.net'] = {
  2919. now: () => scriptLander(() => {
  2920. let nt = new nullTools();
  2921. nt.define(win, 'holder', function(id) {
  2922. let div = _document.getElementById(id);
  2923. if (!div)
  2924. return;
  2925. if (div.parentNode.classList.contains('col__sidebar')) {
  2926. div.parentNode.appendChild(div);
  2927. div.style.height = '300px';
  2928. }
  2929. });
  2930. }, nullTools),
  2931. dom: () => {
  2932. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  2933. frame.parentNode.style.width = '1px';
  2934. }
  2935. };
  2936.  
  2937. scripts['mail.ru'] = {
  2938. other: ['ok.ru'],
  2939. now: () => scriptLander(() => {
  2940. let nt = new nullTools();
  2941. // Trick to prevent mail.ru from removing 3rd-party styles
  2942. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2943. // Disable some of their counters
  2944. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2945. if (location.hostname === 'e.mail.ru')
  2946. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2947. else
  2948. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2949.  
  2950. {
  2951. let missingCheck = {
  2952. get: (obj, name) => {
  2953. if (!(name in obj))
  2954. console.warn(obj, 'missing:', name);
  2955. return obj[name];
  2956. }
  2957. };
  2958. let redefiner = {
  2959. apply: (target, thisArg, args) => {
  2960. let res = void 0;
  2961. let skipLog = (name, ret) => (...args) => (console.log(`Skip ${name}(`, ...args, ')'), ret);
  2962. if (target._name === 'mrg-smokescreen/Welter')
  2963. res = {
  2964. isWelter: () => true,
  2965. wrap: skipLog(`${target._name}.wrap`)
  2966. };
  2967. if (target._name === 'mrg-smokescreen/StyleSheets')
  2968. res = {
  2969. update: skipLog(`${target._name}.update`),
  2970. remove: skipLog(`${target._name}.remove`),
  2971. insert: skipLog(`${target._name}.insert`),
  2972. setup: skipLog(`${target._name}.setup`)
  2973. };
  2974. if (target._name === 'mrg-honeypot/main')
  2975. res = {
  2976. check: skipLog(`${target._name}.check`, false)
  2977. };
  2978. if (target._name.startsWith('advert/rb/slot'))
  2979. res = {
  2980. slot: '0',
  2981. get: () => null,
  2982. getHTML: () => null,
  2983. createBlock: () => null,
  2984. onRedirect: () => null
  2985. };
  2986. if (target._name.startsWith('OK/banners/'))
  2987. res = {
  2988. activate: skipLog(`${target._name}.activate`),
  2989. deactivate: skipLog(`${target._name}.deactivate`)
  2990. };
  2991. if (res)
  2992. res = new Proxy(res, missingCheck);
  2993. else
  2994. res = target.apply(thisArg, args);
  2995. if (target._name === 'advert/RB') {
  2996. res.getSlots = () => [];
  2997. res.load._name = target._name + '.load';
  2998. res.load = new Proxy(res.load, redefiner);
  2999. }
  3000. console.log(target._name, '(',...args,') >>', res);
  3001. return res;
  3002. }
  3003. };
  3004.  
  3005. let wrapAdFuncs = {
  3006. apply: (target, thisArg, args) => {
  3007. let module = args[0];
  3008. if (typeof module === 'string')
  3009. if (module.startsWith('mrg-smoke') ||
  3010. module.startsWith('mrg-context') ||
  3011. module.startsWith('mrg-honeypot') ||
  3012. module.startsWith('advert') ||
  3013. module.startsWith('OK/banner') ||
  3014. module === 'OK/Smokescreen') {
  3015. let fun = args[args.length-1];
  3016. fun._name = module;
  3017. args[args.length-1] = new Proxy(fun, redefiner);
  3018. }// else
  3019. // console.log('Define:', args[0]);
  3020. return target.apply(thisArg, args);
  3021. }
  3022. };
  3023. let wrapDefine = def => {
  3024. if (!def)
  3025. return;
  3026. console.log('define =', def);
  3027. def = new Proxy(def, wrapAdFuncs);
  3028. def._name = 'define';
  3029. return def;
  3030. };
  3031. let _define = wrapDefine(win.define);
  3032. Object.defineProperty(win, 'define', {
  3033. get: () => _define,
  3034. set: x => {
  3035. if (_define === x)
  3036. return true;
  3037. _define = wrapDefine(x);
  3038. return true;
  3039. }
  3040. });
  3041. }
  3042.  
  3043. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3044. let logger = {
  3045. apply: (target, thisArg, args) => {
  3046. let res = target.apply(thisArg, args);
  3047. console.log(`${target._name}(`, ...args, `) >>`, res);
  3048. return res;
  3049. }
  3050. };
  3051.  
  3052. function defineLocator(root) {
  3053. let _locator;
  3054.  
  3055. function wrapLocator(locator) {
  3056. if ('setup' in locator) {
  3057. let _setup = locator.setup;
  3058. locator.setup = function(o) {
  3059. if ('enable' in o) {
  3060. o.enable = false;
  3061. console.log('Disable mimic mode.');
  3062. }
  3063. if ('links' in o) {
  3064. o.links = [];
  3065. console.log('Call with empty list of sheets.');
  3066. }
  3067. return _setup.call(this, o);
  3068. };
  3069. locator.insertSheet = () => false;
  3070. locator.wrap = () => false;
  3071. }
  3072. try {
  3073. let names = [];
  3074. for (let name in locator)
  3075. if (locator[name] instanceof Function && name !== 'transform') {
  3076. locator[name]._name = "locator." + name;
  3077. locator[name] = new Proxy(locator[name], logger);
  3078. names.push(name);
  3079. }
  3080. console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3081. } catch(e) {
  3082. console.log(e);
  3083. }
  3084. _locator = locator;
  3085. }
  3086.  
  3087. if ('locator' in root && root.locator) {
  3088. console.log('Found existing "locator" object. :|', root.locator);
  3089. wrapLocator(root.locator);
  3090. }
  3091.  
  3092. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3093. if (!loc_desc || loc_desc.set !== wrapLocator)
  3094. try {
  3095. Object.defineProperty(root, 'locator', {
  3096. set: wrapLocator,
  3097. get: () => _locator
  3098. });
  3099. } catch (err) {
  3100. console.log('Unable to redefine "locator" object!!!', err);
  3101. }
  3102. }
  3103.  
  3104. function defineDetector(mr) {
  3105. let _honeyPot;
  3106. let __ = mr._ || {};
  3107. let check = function() {
  3108. __.STUCK_IN_POT = false;
  3109. return false;
  3110. };
  3111. check._name = 'honeyPot.check';
  3112. let setHoneyPot = o => {
  3113. console.log('[honeyPot]', o);
  3114. o.check = new Proxy(check, logger);
  3115. _honeyPot = o;
  3116. };
  3117. if ('honeyPot' in mr)
  3118. setHoneyPot(mr.honeyPot);
  3119. Object.defineProperty(mr, 'honeyPot', {
  3120. get: () => _honeyPot,
  3121. set: setHoneyPot
  3122. });
  3123.  
  3124. __ = new Proxy(__, {
  3125. get: (t, p) => t[p],
  3126. set: (t, p, v) => {
  3127. console.log(`mr._.${p} =`, v);
  3128. t[p] = v;
  3129. return true;
  3130. }
  3131. });
  3132. mr._ = __;
  3133. }
  3134.  
  3135. function defineAdd(mr) {
  3136. let _add;
  3137. let addWrapper = {
  3138. apply: (tgt, that, args) => {
  3139. let module = args[0];
  3140. if (module.startsWith('ad')) {
  3141. console.log('Skip module:', module);
  3142. return;
  3143. }
  3144. return logger.apply(tgt, that, args);
  3145. }
  3146. };
  3147. let setMrAdd = v => {
  3148. v._name = 'mr.add';
  3149. v = new Proxy(v, addWrapper);
  3150. _add = v;
  3151. };
  3152. if ('add' in mr)
  3153. setMrAdd(mr.add);
  3154. Object.defineProperty(mr, 'add', {
  3155. get: () => _add,
  3156. set: setMrAdd
  3157. });
  3158.  
  3159. }
  3160.  
  3161. try {
  3162. let _mr;
  3163. Object.defineProperty(win, 'mr', {
  3164. enumerable: true,
  3165. get: () => _mr,
  3166. set: (v) => {
  3167. if (v === _mr)
  3168. return true;
  3169. console.log('Trapped new "mr" object.');
  3170. defineLocator(v.mimic ? v.mimic : v);
  3171. defineDetector(v);
  3172. defineAdd(v);
  3173. _mr = v;
  3174. }
  3175. });
  3176. if (!('mr' in win))
  3177. throw 'Wat!?';
  3178. } catch (e) {
  3179. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  3180. defineLocator(win.mr);
  3181. defineDetector(win.mr);
  3182. defineAdd(win.mr);
  3183. }
  3184.  
  3185. // smokyTools wrapper for news.mail.ru
  3186. nt.define(win, 'smokyTools', nt.proxy({
  3187. Selector: nt.func(null),
  3188. getDict: nt.func(nt.proxy({
  3189. attrLookup: nt.func(null),
  3190. classLookup: nt.func(null)
  3191. })),
  3192. CSS: nt.func(nt.proxy({
  3193. addAllCssToIndex: nt.func(null),
  3194. addCssToIndex: nt.func(null),
  3195. smokeClass: nt.func(null)
  3196. }))
  3197. }));
  3198. nt.define(win, 'smoky', nt.func(null));
  3199. nt.define(win, 'smokySingleElement', nt.func(null));
  3200. nt.define(win, 'smokyByClass', nt.func(null));
  3201. }, nullTools)
  3202. };
  3203.  
  3204. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3205. let _rmpGlobals = void 0;
  3206. Object.defineProperty(win, 'rmpGlobals', {
  3207. get: () => _rmpGlobals,
  3208. set: x => {
  3209. if (x === _rmpGlobals)
  3210. return true;
  3211. _rmpGlobals = new Proxy(x, {
  3212. get: (obj, name) => {
  3213. if (name === 'adBlockerDetected')
  3214. return false;
  3215. return obj[name];
  3216. },
  3217. set: (obj, name, val) => {
  3218. if (name === 'adBlockerDetected')
  3219. console.warn('rmpGlobals.adBlockerDetected =', val)
  3220. else
  3221. obj[name] = val;
  3222. return true;
  3223. }
  3224. });
  3225. }
  3226. });
  3227. });
  3228.  
  3229. scripts['megogo.net'] = {
  3230. now: () => {
  3231. let nt = new nullTools();
  3232. nt.define(win, 'adBlock', false);
  3233. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3234. }
  3235. };
  3236.  
  3237. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3238.  
  3239. scripts['newdeaf-online.net'] = {
  3240. dom: () => {
  3241. let adNodes = _document.querySelectorAll('.ads');
  3242. if (!adNodes)
  3243. return;
  3244. let getter = x => {
  3245. let val = x;
  3246. return () => (console.warn('read .ads', name, val), val);
  3247. };
  3248. let setter = x => console.warn('skip write .ads', name, x);
  3249. for (let adNode of adNodes)
  3250. for (let name of ['innerHTML'])
  3251. Object.defineProperty(adNode, name, {
  3252. get: getter(ads[name]),
  3253. set: setter
  3254. });
  3255. }
  3256. };
  3257.  
  3258. scripts['overclockers.ru'] = {
  3259. dom: () => scriptLander(() => {
  3260. let killed = () => console.warn('Anti-Adblock killed.');
  3261. if ('$' in win)
  3262. win.$ = new Proxy($, {
  3263. apply: (tgt, that, args) => {
  3264. let res = tgt.apply(that, args);
  3265. if (res[0] && res[0] === _document.body) {
  3266. res.html = killed;
  3267. res.empty = killed;
  3268. }
  3269. return res;
  3270. }
  3271. });
  3272. })
  3273. };
  3274. scripts['forums.overclockers.ru'] = {
  3275. now: () => {
  3276. createStyle('.needblock {position: fixed; left: -10000px}');
  3277. Object.defineProperty(win, 'adblck', {
  3278. get: () => 'no',
  3279. set: () => undefined,
  3280. enumerable: true
  3281. });
  3282. }
  3283. };
  3284.  
  3285. scripts['pb.wtf'] = {
  3286. other: ['piratbit.org', 'piratbit.ru'],
  3287. dom: () => {
  3288. // line above topic content and images in the slider in the header
  3289. let remove = node => (console.log('removed', node), node.parentNode.removeChild(node));
  3290. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3291. if (location.hostname === el.hostname &&
  3292. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3293. remove(el.closest('div, tr'));
  3294. continue;
  3295. }
  3296. // ads in the topic header in case filter above wasn't enough
  3297. let parent = el.closest('tr');
  3298. if (parent) {
  3299. let span = (parent.querySelector('span') || {}).textContent;
  3300. span && span.startsWith('YO!') && remove(parent);
  3301. }
  3302. }
  3303. // casino ad button in random places
  3304. for (let el of _document.querySelectorAll('.btn-group')) {
  3305. el = el.parentNode;
  3306. if (el.tagName === 'CENTER')
  3307. remove(el.parentNode);
  3308. }
  3309. // ads in comments
  3310. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3311. if (el && el.parentNode.children[2] == el)
  3312. remove(el);
  3313. }
  3314. };
  3315.  
  3316. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3317.  
  3318. scripts['peka2.tv'] = () => {
  3319. let bodyClass = 'body--branding';
  3320. let checkNode = node => {
  3321. for (let className of node.classList)
  3322. if (className.includes('banner') || className === bodyClass) {
  3323. _removeAttribute(node, 'style');
  3324. node.classList.remove(className);
  3325. for (let attr of Array.from(node.attributes))
  3326. if (attr.name.startsWith('advert'))
  3327. _removeAttribute(node, attr.name);
  3328. }
  3329. };
  3330. (new MutationObserver(ms => {
  3331. let m, node;
  3332. for (m of ms) for (node of m.addedNodes)
  3333. if (node instanceof HTMLElement)
  3334. checkNode(node);
  3335. })).observe(_de, {childList: true, subtree: true});
  3336. (new MutationObserver(ms => {
  3337. for (let m of ms)
  3338. checkNode(m.target);
  3339. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3340. };
  3341.  
  3342. scripts['qrz.ru'] = {
  3343. now: () => {
  3344. let nt = new nullTools();
  3345. nt.define(win, 'ab', false);
  3346. nt.define(win, 'tryMessage', nt.func(null));
  3347. }
  3348. };
  3349.  
  3350. scripts['razlozhi.ru'] = {
  3351. now: () => {
  3352. for (let func of ['createShadowRoot', 'attachShadow'])
  3353. if (func in _Element.prototype)
  3354. _Element.prototype[func] = function(){
  3355. return this.cloneNode();
  3356. };
  3357. }
  3358. };
  3359.  
  3360. scripts['rbc.ru'] = {
  3361. other: ['rbcplus.ru', 'sportrbc.ru'],
  3362. now: () => {
  3363. selectiveCookies('adb_on');
  3364. let _RA = void 0;
  3365. let setArgs = {
  3366. 'showBanners': true,
  3367. 'showAds': true,
  3368. 'paywall.user.logined': true,
  3369. 'paywall.user.paid': true,
  3370. 'banners.staticPath': '',
  3371. 'paywall.staticPath': '',
  3372. 'banners.dfp.config': [],
  3373. 'banners.dfp.pageTargeting': () => null,
  3374. };
  3375. Object.defineProperty(win, 'RA', {
  3376. get: () => _RA,
  3377. set: vl => {
  3378. console.log('RA =', vl);
  3379. if ('repo' in vl) {
  3380. console.log('RA.repo =', vl.repo);
  3381. vl.repo = new Proxy(vl.repo, {
  3382. set: (o, name, val) => {
  3383. if (name === 'banner') {
  3384. console.log(`RA.repo.${name} =`, val);
  3385. val = new Proxy(val, {
  3386. get: (o, name) => {
  3387. let res = o[name];
  3388. if (typeof o[name] === 'function')
  3389. res = () => null;
  3390. if (name === 'isInited')
  3391. res = true;
  3392. console.warn(`get RA.repo.banner.${name}`, res);
  3393. return res;
  3394. }
  3395. });
  3396. }
  3397. o[name] = val;
  3398. return true;
  3399. }
  3400. });
  3401. } else
  3402. console.log('Unable to locate RA.repo');
  3403. _RA = new Proxy(vl, {
  3404. set: (o, name, val) => {
  3405. if (name === 'config') {
  3406. console.log('RA.config =', val);
  3407. if ('set' in val) {
  3408. val.set = new Proxy(val.set, {
  3409. apply: (set, that, args) => {
  3410. let name = args[0];
  3411. if (name in setArgs)
  3412. args[1] = setArgs[name];
  3413. if (name in setArgs || name === 'checkad')
  3414. console.log('RA.config.set(', ...args, ')');
  3415. return Reflect.apply(set, that, args);
  3416. }
  3417. });
  3418. val.set('showAds', true); // pretend ads already were shown
  3419. }
  3420. }
  3421. o[name] = val;
  3422. return true;
  3423. }
  3424. });
  3425. }
  3426. });
  3427. Object.defineProperty(win, 'bannersConfig', {
  3428. get: () => [], set: () => null
  3429. });
  3430. // pretend there is a paywall landing on screen already
  3431. let pwl = _document.createElement('div');
  3432. pwl.style.display = 'none';
  3433. pwl.className = 'js-paywall-landing';
  3434. _document.documentElement.appendChild(pwl);
  3435. // detect and skip execution of one of the ABP detectors
  3436. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3437. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3438. win.setTimeout = function setTimeout() {
  3439. if (typeof arguments[0] === 'function') {
  3440. let fts = _toString(arguments[0]);
  3441. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  3442. console.log('Skipped setTimout(', fts, arguments[1], ')');
  3443. return;
  3444. }
  3445. }
  3446. return _setTimeout(this, arguments);
  3447. };
  3448. }
  3449. };
  3450.  
  3451. scripts['rp5.ru'] = {
  3452. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3453. now: () => {
  3454. Object.defineProperty(win, 'sContentBottom', {
  3455. get: () => '',
  3456. set: () => true
  3457. });
  3458. }
  3459. };
  3460.  
  3461. scripts['rutube.ru'] = () => scriptLander(() => {
  3462. let _parse = JSON.parse;
  3463. let _skip_enabled = false;
  3464. JSON.parse = (...args) => {
  3465. let res = _parse(...args),
  3466. log = false;
  3467. if (!res)
  3468. return res;
  3469. // parse player configuration
  3470. if ('appearance' in res || 'video_balancer' in res) {
  3471. log = true;
  3472. if (res.appearance) {
  3473. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3474. res.appearance.forbid_seek = false;
  3475. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3476. res.appearance.forbid_timeline_preview = false;
  3477. }
  3478. _skip_enabled = !!res.remove_unseekable_blocks;
  3479. //res.advert = [];
  3480. delete res.advert;
  3481. //for (let limit of res.limits)
  3482. // limit.limit = 0;
  3483. delete res.limits;
  3484. //res.yast = null;
  3485. //res.yast_live_online = null;
  3486. delete res.yast;
  3487. delete res.yast_live_online;
  3488. Object.defineProperty(res, 'stat', {
  3489. get: () => [],
  3490. set: () => true,
  3491. enumerable: true
  3492. });
  3493. }
  3494.  
  3495. // parse video configuration
  3496. if ('video_url' in res) {
  3497. log = true;
  3498. if (res.cuepoints && !_skip_enabled)
  3499. for (let point of res.cuepoints) {
  3500. point.is_pause = false;
  3501. point.show_navigation = true;
  3502. point.forbid_seek = false;
  3503. }
  3504. }
  3505.  
  3506. if (log)
  3507. console.log('[rutube]', res);
  3508. return res;
  3509. };
  3510. });
  3511.  
  3512. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3513. let _addEventListener = _Document.prototype.addEventListener;
  3514. _document.addEventListener = function(event, callback) {
  3515. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3516. return;
  3517. return _addEventListener.apply(this, arguments);
  3518. };
  3519. });
  3520.  
  3521. scripts['smotret-anime.ru'] = () => scriptLander(() => {
  3522. deepWrapAPI(root => {
  3523. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3524. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3525. let stopper = e => _pause(e.target);
  3526. root.Audio = new Proxy(root.Audio, {
  3527. construct: (audio, args) => {
  3528. let res = new audio(...args);
  3529. _addEventListener(res, 'play', stopper, true);
  3530. return res;
  3531. }
  3532. });
  3533. _createElement = root.Document.prototype.createElement;
  3534. root.Document.prototype.createElement = function createElement() {
  3535. let res = _createElement.apply(this, arguments);
  3536. if (res instanceof HTMLAudioElement)
  3537. _addEventListener(res, 'play', stopper, true);
  3538. return res;
  3539. };
  3540. });
  3541. }, deepWrapAPI);
  3542.  
  3543. scripts['spaces.ru'] = () => {
  3544. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3545. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3546. };
  3547.  
  3548. scripts['spam-club.blogspot.co.uk'] = () => {
  3549. let _clientHeight = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientHeight'),
  3550. _clientWidth = Object.getOwnPropertyDescriptor(_Element.prototype, 'clientWidth');
  3551. let wrapGetter = (getter) => {
  3552. let _getter = getter;
  3553. return function() {
  3554. let _size = _getter.apply(this, arguments);
  3555. return _size ? _size : 1;
  3556. };
  3557. };
  3558. _clientHeight.get = wrapGetter(_clientHeight.get);
  3559. _clientWidth.get = wrapGetter(_clientWidth.get);
  3560. Object.defineProperty(_Element.prototype, 'clientHeight', _clientHeight);
  3561. Object.defineProperty(_Element.prototype, 'clientWidth', _clientWidth);
  3562. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3563. _set_onload = _onload.set;
  3564. _onload.set = function() {
  3565. if (this instanceof HTMLImageElement)
  3566. return true;
  3567. _set_onload.apply(this, arguments);
  3568. };
  3569. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3570. };
  3571.  
  3572. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3573.  
  3574. scripts['sports.ru'] = {
  3575. now: () => {
  3576. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3577. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3578. // extra functionality: shows/hides panel at the top depending on scroll direction
  3579. createStyle([
  3580. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3581. '.user-panel-up { top: -40px!important }'
  3582. ], {id: 'userPanelSlide'}, false);
  3583. },
  3584. dom: () => {
  3585. (function lookForPanel() {
  3586. let panel = _document.querySelector('.user-panel__fixed');
  3587. if (!panel)
  3588. setTimeout(lookForPanel, 100);
  3589. else
  3590. window.addEventListener(
  3591. 'wheel', function(e) {
  3592. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3593. panel.classList.add('user-panel-up');
  3594. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3595. panel.classList.remove('user-panel-up');
  3596. }, false
  3597. );
  3598. })();
  3599. }
  3600. };
  3601.  
  3602. scripts['stealthz.ru'] = {
  3603. dom: () => {
  3604. // skip timeout
  3605. let $ = _document.querySelector.bind(_document);
  3606. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3607. if (!timer_1 || !timer_2)
  3608. return;
  3609. timer_1.style.display = 'none';
  3610. timer_2.style.display = 'block';
  3611. }
  3612. };
  3613.  
  3614. scripts['xittv.net'] = () => scriptLander(() => {
  3615. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  3616. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  3617. let _jwplayer = void 0;
  3618. Object.defineProperty(win, 'jwplayer', {
  3619. get: () => _jwplayer,
  3620. set: x => {
  3621. _jwplayer = new Proxy(x, {
  3622. apply: (fun, that, args) => {
  3623. let res = fun.apply(that, args);
  3624. res = new Proxy(res, {
  3625. get: (obj, name) => {
  3626. if (logNames.includes(name) && obj[name] instanceof Function)
  3627. return new Proxy(obj[name], {
  3628. apply: (fun, that, args) => {
  3629. if (name === 'setup') {
  3630. let o = args[0];
  3631. if (o)
  3632. delete o.advertising;
  3633. }
  3634. if (name === 'on' || name === 'trigger') {
  3635. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  3636. if (events.length === 1 && skipEvents.includes(events[0]))
  3637. return res;
  3638. if (events.length > 1) {
  3639. let names = [];
  3640. for (let event of events)
  3641. if (!skipEvents.includes(event))
  3642. names.push(event);
  3643. if (names.length > 0)
  3644. args[0] = names.join(" ");
  3645. else
  3646. return res;
  3647. }
  3648. }
  3649. let subres = fun.apply(that, args);
  3650. console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  3651. return subres;
  3652. }
  3653. });
  3654. return obj[name];
  3655. }
  3656. });
  3657. return res;
  3658. }
  3659. });
  3660. console.log('jwplayer =', x);
  3661. }
  3662. });
  3663. });
  3664.  
  3665. scripts['yap.ru'] = {
  3666. other: ['yaplakal.com'],
  3667. now: () => {
  3668. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3669. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3670. }
  3671. };
  3672.  
  3673. scripts['rambler.ru'] = {
  3674. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  3675. now: () => scriptLander(() => {
  3676. // Prevent autoplay
  3677. if (!('EaglePlayer' in win)) {
  3678. let _EaglePlayer = void 0;
  3679. Object.defineProperty(win, 'EaglePlayer', {
  3680. enumerable: true,
  3681. get: () => _EaglePlayer,
  3682. set: x => {
  3683. if (x === _EaglePlayer)
  3684. return true;
  3685. _EaglePlayer = new Proxy(x, {
  3686. construct: (targ, args) => {
  3687. let player = new targ(...args);
  3688. if (!player.options) {
  3689. console.log('EaglePlayer: no options', EaglePlayer);
  3690. return player;
  3691. }
  3692. Object.defineProperty(player.options, 'autoplay', {
  3693. get: () => false,
  3694. set: () => true
  3695. });
  3696. Object.defineProperty(player.options, 'scroll', {
  3697. get: () => false,
  3698. set: () => true
  3699. });
  3700. return player;
  3701. }
  3702. });
  3703. }
  3704. });
  3705. let _setAttribute = Function.prototype.apply.bind(_Element.prototype.setAttribute);
  3706. let isAutoplay = /^autoplay$/i;
  3707. _Element.prototype.setAttribute = function setAttribute(name) {
  3708. if (!this._stopped && isAutoplay.test(name)) {
  3709. console.log('Prevented assigning autoplay attribute.');
  3710. return null;
  3711. }
  3712. return _setAttribute(this, arguments);
  3713. };
  3714. } else {
  3715. console.log('EaglePlayer function already exists.');
  3716. if (inIFrame) {
  3717. let _setAttribute = Function.prototype.apply.bind(_Element.prototype.setAttribute);
  3718. let isAutoplay = /^autoplay$/i;
  3719. _Element.prototype.setAttribute = function setAttribute(name) {
  3720. if (!this._stopped && isAutoplay.test(name)) {
  3721. console.log('Prevented assigning autoplay attribute.');
  3722. this._stopped = true;
  3723. this.play = () => {
  3724. console.log('Prevented attempt to force-start playback.');
  3725. delete this.play;
  3726. };
  3727. return null;
  3728. }
  3729. return _setAttribute(this, arguments);
  3730. };
  3731. }
  3732. }
  3733. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3734. return;
  3735. // prevent ads from loading
  3736. let blockObfuscated = false;
  3737. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  3738. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3739. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3740. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3741. let _cssText_get = _cssText.get;
  3742. _cssText.configurable = false;
  3743. _cssText.get = function() {
  3744. let cssText = _cssText_get.call(this);
  3745. if (cssText.includes('content:')) {
  3746. console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3747. blockObfuscated = true;
  3748. return null;
  3749. }
  3750. return cssText;
  3751. };
  3752. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3753. let _setTimeout = win.setTimeout;
  3754. win.setTimeout = function(f) {
  3755. if (blockObfuscated && obfuscation.test(_toString(f))) {
  3756. console.warn('Stopped setTimeout for:', _toString(f).slice(0,100), '\u2026');
  3757. return null;
  3758. };
  3759. return _setTimeout.apply(this, arguments);
  3760. };
  3761. // fake global Adf object
  3762. let nt = new nullTools();
  3763. let Adf_banner = {};
  3764. [
  3765. 'reloadssp', 'sspScroll',
  3766. 'sspRich', 'ssp'
  3767. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3768. nt.define(win, 'Adf', nt.proxy({
  3769. banner: nt.proxy(Adf_banner)
  3770. }));
  3771. // extra script to remove partner news on gazeta.ru
  3772. if (!location.hostname.includes('gazeta.ru'))
  3773. return;
  3774. (new MutationObserver(
  3775. (ms) => {
  3776. let m, node, header;
  3777. for (m of ms) for (node of m.addedNodes)
  3778. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3779. header = node.querySelector('.sausage-header');
  3780. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3781. node.style.display = 'none';
  3782. }
  3783. }
  3784. )).observe(_document.documentElement, { childList:true, subtree: true });
  3785. }, `let inIFrame = ${inIFrame}`, nullTools)
  3786. };
  3787.  
  3788. scripts['reactor.cc'] = {
  3789. other: ['joyreactor.cc', 'pornreactor.cc'],
  3790. now: () => {
  3791. selectiveEval();
  3792. scriptLander(() => {
  3793. let nt = new nullTools();
  3794. win.open = function(){
  3795. throw new Error('Redirect prevention.');
  3796. };
  3797. nt.define(win, 'Worker', function(){});
  3798. nt.define(win, 'JRCH', win.CoinHive);
  3799. }, nullTools);
  3800. },
  3801. click: function(e) {
  3802. let node = e.target;
  3803. if (node.nodeType === _Node.ELEMENT_NODE &&
  3804. node.style.position === 'absolute' &&
  3805. node.style.zIndex > 0)
  3806. node.parentNode.removeChild(node);
  3807. },
  3808. dom: function() {
  3809. let words = new RegExp(
  3810. 'блокировщик рекламы'
  3811. .split('')
  3812. .map(function(e){
  3813. return e+'[\u200b\u200c\u200d]*';
  3814. })
  3815. .join('')
  3816. .replace(' ', '\\s*')
  3817. .replace(/[аоре]/g, function(e){
  3818. return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];
  3819. }),
  3820. 'i'),
  3821. can;
  3822. function deeper(spider) {
  3823. for (let child of spider.childNodes)
  3824. if (words.test(child.innerText))
  3825. if (child.offsetHeight >= 750)
  3826. deeper(child);
  3827. else
  3828. can.push(child);
  3829. }
  3830. function probe() {
  3831. can = [];
  3832. deeper(_document.body);
  3833. for (let spider of can)
  3834. _setAttribute(spider, 'style', 'background:none!important');
  3835. }
  3836. (new MutationObserver(probe))
  3837. .observe(_document, { childList:true, subtree:true });
  3838. }
  3839. };
  3840.  
  3841. scripts['auto.ru'] = () => {
  3842. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3843. let userAdsListAds = (
  3844. '.listing-list > .listing-item,'+
  3845. '.listing-item_type_fixed.listing-item'
  3846. );
  3847. let catalogAds = (
  3848. 'div[class*="layout_catalog-inline"],'+
  3849. 'div[class$="layout_horizontal"]'
  3850. );
  3851. let otherAds = (
  3852. '.advt_auto,'+
  3853. '.sidebar-block,'+
  3854. '.pager-listing + div[class],'+
  3855. '.card > div[class][style],'+
  3856. '.sidebar > div[class],'+
  3857. '.main-page__section + div[class],'+
  3858. '.listing > tbody'
  3859. );
  3860. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3861. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3862. gardener(otherAds, words);
  3863. };
  3864.  
  3865. scripts['rsload.net'] = {
  3866. load: () => {
  3867. let dis = _document.querySelector('label[class*="cb-disable"]');
  3868. if (dis)
  3869. dis.click();
  3870. },
  3871. click: e => {
  3872. let t = e.target;
  3873. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3874. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3875. }
  3876. };
  3877.  
  3878. let domain;
  3879. // add alternative domain names if present and wrap functions into objects
  3880. for (let name in scripts) {
  3881. if (scripts[name] instanceof Function)
  3882. scripts[name] = { now: scripts[name] };
  3883. for (domain of (scripts[name].other||[])) {
  3884. if (domain in scripts)
  3885. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3886. scripts[domain] = scripts[name];
  3887. }
  3888. delete scripts[name].other;
  3889. }
  3890. // look for current domain in the list and run appropriate code
  3891. domain = _document.domain;
  3892. while (domain.includes('.')) {
  3893. if (domain in scripts) for (let when in scripts[domain])
  3894. switch(when) {
  3895. case 'now':
  3896. scripts[domain][when]();
  3897. break;
  3898. case 'dom':
  3899. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3900. break;
  3901. default:
  3902. _document.addEventListener (when, scripts[domain][when], false);
  3903. }
  3904. domain = domain.slice(domain.indexOf('.') + 1);
  3905. }
  3906.  
  3907. // Batch script lander
  3908. if (!skipLander)
  3909. landScript(batchLand, batchPrepend);
  3910.  
  3911. { // JS Fixes Tools Menu
  3912. let openOptions = function() {
  3913. let ovl = _createElement('div'),
  3914. inner = _createElement('div');
  3915. ovl.style = (
  3916. 'position: fixed;'+
  3917. 'top:0; left:0;'+
  3918. 'bottom: 0; right: 0;'+
  3919. 'background: rgba(0,0,0,0.85);'+
  3920. 'z-index: 2147483647;'+
  3921. 'padding: 5em'
  3922. );
  3923. inner.style = (
  3924. 'background: whitesmoke;'+
  3925. 'font-size: 10pt;'+
  3926. 'color: black;'+
  3927. 'padding: 1em'
  3928. );
  3929. inner.textContent = 'JS Fixes Tools';
  3930. inner.appendChild(_createElement('br'));
  3931. inner.appendChild(_createElement('br'));
  3932. ovl.addEventListener(
  3933. 'click', function(e) {
  3934. if (e.target === ovl) {
  3935. ovl.parentNode.removeChild(ovl);
  3936. e.preventDefault();
  3937. }
  3938. e.stopPropagation();
  3939. }, false
  3940. );
  3941.  
  3942. let sObjBtn = _createElement('button');
  3943. sObjBtn.onclick = getStrangeObjectsList;
  3944. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  3945. inner.appendChild(_createElement('br'));
  3946. inner.appendChild(sObjBtn);
  3947.  
  3948. _document.body.appendChild(ovl);
  3949. ovl.appendChild(inner);
  3950. };
  3951.  
  3952. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  3953. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  3954. _document.addEventListener(
  3955. 'keydown', function(e) {
  3956. if ((e.code === opKey[opPos] || e.location) &&
  3957. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  3958. opPos += e.location ? 0 : 1;
  3959. e.stopPropagation();
  3960. e.preventDefault();
  3961. } else
  3962. opPos = 0;
  3963. if (opPos === opKey.length) {
  3964. opPos = 0;
  3965. openOptions();
  3966. }
  3967. }, false
  3968. );
  3969. }
  3970. })();