RU AdList JS Fixes

try to take over the world!

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

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