RU AdList JS Fixes

try to take over the world!

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

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