RU AdList JS Fixes

try to take over the world!

目前為 2019-01-30 提交的版本,檢視 最新版本

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