RU AdList JS Fixes

try to take over the world!

当前为 2019-01-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20190123.4
  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',
  1082. 'sendCounts', '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.',
  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. scPattern = new RegExp(`(^|;\\s?)(${scPattern}|${ga})($|=)`);
  2083. if (isFirefox && scPaths.length)
  2084. scPaths = scPaths.map(path => `${path}/`);
  2085. scPaths.push('/');
  2086. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  2087. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2088. if (_cookie) {
  2089. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  2090. let _get_cookie = Function.prototype.call.bind(_cookie.get);
  2091. let expireDate = 'Thu, 01 Jan 1970 00:00:01 UTC';
  2092. let expireAge = '-99999999';
  2093. let expireBase = `=;expires=${expireDate};Max-Age=${expireAge}`;
  2094. let expireAttempted = {};
  2095. // expire is called from cookie getter and doesn't know exact parameters used to set cookies present there
  2096. // so, it will use path=/ by default if scPaths wasn't set and attempt to set cookies on all parent domains
  2097. let expire = (cookie, that) => {
  2098. let domain = that.location.hostname.split('.'),
  2099. name = cookie.replace(/=.*/,'');
  2100. scPaths.forEach(path =>_set_cookie(that, `${name}${expireBase};path=${path}`));
  2101. while (domain.length > 1) {
  2102. try {
  2103. scPaths.forEach(
  2104. path => _set_cookie(that, `${name}${expireBase};domain=${domain.join('.')};path=${path}`)
  2105. );
  2106. } catch(e) { _console.warn(e); }
  2107. domain.shift();
  2108. }
  2109. expireAttempted[name] = true;
  2110. _console.log('Removing existing cookie:', cookie);
  2111. };
  2112. // skip setting unwanted cookies
  2113. _cookie.set = function(value) {
  2114. if (scPattern.test(value)) {
  2115. _console.warn('Ignored cookie:', value);
  2116. // try to remove same cookie if it already exists using exact values from the set string
  2117. if (scPattern.test(_get_cookie(this))) {
  2118. let parts = value.split(/;\s?/),
  2119. name = parts[0].replace(/=.*/,''),
  2120. newParts = [`${name}=`, `expires=${expireDate}`, `Max-Age=${expireAge}`],
  2121. skip = [name, 'expires', 'Max-Age'];
  2122. for (let part of parts)
  2123. if (!skip.includes(part.replace(/=.*/,'')))
  2124. newParts.push(part);
  2125. try {
  2126. _set_cookie(this, newParts.join(';'));
  2127. } catch(e) { _console.warn(e); }
  2128. _console.log('Removing existing cookie:', name);
  2129. }
  2130. return;
  2131. }
  2132. return _set_cookie(this, value);
  2133. };
  2134. // hide unwanted cookies from site
  2135. _cookie.get = function() {
  2136. let res = _get_cookie(this);
  2137. if (scPattern.test(res)) {
  2138. let stack = [];
  2139. for (let cookie of res.split(/;\s?/))
  2140. if (!scPattern.test(cookie))
  2141. stack.push(cookie);
  2142. else {
  2143. let name = cookie.replace(/=.*/,'');
  2144. if (expireAttempted[name]) {
  2145. _console.log('Unable to expire:', cookie);
  2146. expireAttempted[name] = false;
  2147. }
  2148. if (!(name in expireAttempted))
  2149. expire(cookie, this);
  2150. }
  2151. res = stack.join('; ');
  2152. }
  2153. return res;
  2154. };
  2155. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2156. }
  2157. _console.log('Active cookies:', document.cookie);
  2158. }, `let scPattern = "${scPattern}", scPaths = ${JSON.stringify(scPaths)}, isFirefox = ${isFirefox};`);
  2159. }
  2160.  
  2161. /*{ // simple toString wrapper, might be useful to prevent detection
  2162. '[native code]';
  2163. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2164. let baseText = Function.prototype.toString.toString();
  2165. let protect = new WeakSet();
  2166. protect.add(_Document.createElement);
  2167. protect.add(_Node.appendChild);
  2168. protect.add(_Node.removeChild);
  2169. win.Function.prototype.toString = function() {
  2170. if (protect.has(this))
  2171. return baseText.replace('toString', this.name);
  2172. return _toString(this);
  2173. };
  2174. protect.add(Function.prototype.toString);
  2175. }*/
  2176.  
  2177. // Locates a node with specific text in Russian
  2178. // Uses table of substitutions for similar letters
  2179. let selectNodeByTextContent = (()=> {
  2180. let subs = {
  2181. // english & greek
  2182. 'А': 'AΑ', 'В': 'BΒ', 'Г':'Γ',
  2183. 'Е': 'EΕ', 'З': '3', 'К':'KΚ',
  2184. 'М': 'MΜ', 'Н': 'HΗ', 'О':'OΟ',
  2185. 'П': 'Π', 'Р': 'PΡ', 'С':'C',
  2186. 'Т': 'T', 'Ф': 'Φ', 'Х':'XΧ'
  2187. }
  2188. let regExpBuilder = text => new RegExp(
  2189. text.toUpperCase()
  2190. .split('')
  2191. .map(function(e){
  2192. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2193. })
  2194. .join(''),
  2195. 'i');
  2196. let reMap = {};
  2197. return (re, opts = { root: _document.body }) => {
  2198. if (!re.test) {
  2199. if (!reMap[re])
  2200. reMap[re] = regExpBuilder(re);
  2201. re = reMap[re];
  2202. }
  2203.  
  2204. for (let child of opts.root.children)
  2205. if (re.test(child.textContent)) {
  2206. if (opts.shallow)
  2207. return child;
  2208. opts.root = child;
  2209. return selectNodeByTextContent(re, opts) || child;
  2210. }
  2211. }
  2212. })();
  2213.  
  2214. // === Scripts for specific domains ===
  2215.  
  2216. let scripts = {};
  2217. // prevent popups and redirects block
  2218. // Popups
  2219. scripts.preventPopups = {
  2220. other: [
  2221. 'biqle.ru',
  2222. 'chaturbate.com',
  2223. 'dfiles.ru',
  2224. 'eporner.eu',
  2225. 'hentaiz.org',
  2226. 'mirrorcreator.com',
  2227. 'online-multy.ru',
  2228. 'radikal.ru', 'rumedia.ws',
  2229. 'tapehub.tech', 'thepiratebay.org',
  2230. 'unionpeer.com',
  2231. 'zippyshare.com'
  2232. ],
  2233. now: preventPopups
  2234. };
  2235. // Popunders (background redirect)
  2236. scripts.preventPopunders = {
  2237. other: [
  2238. 'lostfilm-online.ru',
  2239. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2240. 'perfectgirls.net'
  2241. ],
  2242. now: preventPopunders
  2243. };
  2244. // PopMix (both types of popups encountered on site)
  2245. scripts['openload.co'] = {
  2246. other: ['oload.tv', 'oload.info'],
  2247. now: () => {
  2248. let nt = new nullTools();
  2249. nt.define(win, 'CNight', win.CoinHive);
  2250. if (location.pathname.startsWith('/embed/')) {
  2251. nt.define(win, 'BetterJsPop', {
  2252. add: ((a, b) => _console.warn('BetterJsPop.add', a, b)),
  2253. config: ((o) => _console.warn('BetterJsPop.config', o)),
  2254. Browser: { isChrome: true }
  2255. });
  2256. nt.define(win, 'isSandboxed', nt.func(null));
  2257. nt.define(win, 'adblock', false);
  2258. nt.define(win, 'adblock2', false);
  2259. } else preventPopMix();
  2260. }
  2261. };
  2262. scripts['turbobit.net'] = preventPopMix;
  2263.  
  2264. scripts['tapochek.net'] = () => {
  2265. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2266. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2267. let _appendChild_value = _appendChild.value;
  2268. _appendChild.value = function appendChild(node) {
  2269. if (this === _document.body)
  2270. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2271. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2272. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2273. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2274. throw '...eenope!';
  2275. return _appendChild_value.apply(this, arguments);
  2276. };
  2277. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2278.  
  2279. // disable window focus tricks and changing location
  2280. let focusHandlerName = /\WfocusAchieved\(/
  2281. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  2282. let _setInterval = win.setInterval;
  2283. win.setInterval = (...args) => {
  2284. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2285. _console.log('skip setInterval for', ...args);
  2286. return -1;
  2287. }
  2288. return _setInterval(...args);
  2289. };
  2290. let _addEventListener = win.addEventListener;
  2291. win.addEventListener = function(...args) {
  2292. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2293. _console.log('skip addEventListener for', ...args);
  2294. return void 0;
  2295. }
  2296. return _addEventListener.apply(this, args);
  2297. };
  2298.  
  2299. // generic popup prevention
  2300. preventPopups();
  2301. };
  2302.  
  2303. scripts['rustorka.com'] = {
  2304. other: ['rustorka.club', 'rustorka.lib', 'rustorka.net'],
  2305. now: () => {
  2306. selectiveEval(evalPatternGeneric, /antiadblock/);
  2307. selectiveCookies('adblock|u_count|gophp|st2|st3', ['/forum']);
  2308. scriptLander(() => {
  2309. // wrap window.open to catch a popup if it triggers
  2310. win.open = (...args) => {
  2311. _console.warn(`Site attempted to open "${args[0]}" in a new window.`);
  2312. location.replace(location.href);
  2313. return null;
  2314. };
  2315. window.addEventListener('DOMContentLoaded', () => {
  2316. let link = void 0;
  2317. _document.body.addEventListener('mousedown', e => {
  2318. link = e.target.closest('a, select, #fancybox-title-wrap');
  2319. }, false);
  2320. let _open = window.open.bind(window);
  2321. let _getAttribute = Function.prototype.call.bind(_Element.getAttribute);
  2322. win.open = (...args) => {
  2323. let url = args[0];
  2324. if (link instanceof HTMLAnchorElement) {
  2325. // third-party post links
  2326. let href = _getAttribute(link, 'href');
  2327. if (link.classList.contains('postLink') &&
  2328. !link.matches(`a[href*="${location.hostname}"]`) &&
  2329. (href === url || link.href === url))
  2330. return _open(...args);
  2331. // onclick # links
  2332. if (href === '#' && /window\.open/.test(_getAttribute(link, 'onclick')))
  2333. return _open(...args);
  2334. // force local links to load in the current window
  2335. if (href[0] === '/' || href.startsWith('./') || href.includes(`//${location.hostname}/`))
  2336. location.assign(href);
  2337. }
  2338. // list of image hostings under upload picture button (new comment)
  2339. if (link instanceof HTMLSelectElement &&
  2340. !url.includes(location.hostname) &&
  2341. link.value === url)
  2342. return _open(...args);
  2343. // open screenshot in a new window
  2344. if (link instanceof HTMLSpanElement &&
  2345. link.id === 'fancybox-title-wrap')
  2346. return _open(...args);
  2347. // looks like tabunder
  2348. if (link === null && url === location.href)
  2349. location.replace(url); // reload current page
  2350. // other cases
  2351. _console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2352. return {};
  2353. };
  2354. }, true);
  2355. }, nullTools)
  2356. }
  2357. };
  2358.  
  2359. // = other ======================================================================================
  2360. scripts['1tv.ru'] = {
  2361. other: ['mediavitrina.ru'],
  2362. now: () => scriptLander(() => {
  2363. let nt = new nullTools();
  2364. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2365. let disablePlugins = {
  2366. 'antiblock': false,
  2367. 'stat1tv': false
  2368. };
  2369. let _EUMPConfig = void 0;
  2370. let _EUMPConfig_set = x => {
  2371. if (x.plugins) {
  2372. x.plugins = x.plugins.filter(plugin => (plugin in disablePlugins) ? !(disablePlugins[plugin] = true) : true);
  2373. _console.warn(`Player plugins: active [${x.plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2374. }
  2375. _EUMPConfig = x;
  2376. };
  2377. if ('EUMPConfig' in win)
  2378. _EUMPConfig_set(win.EUMPConfig);
  2379. Object.defineProperty(win, 'EUMPConfig', {
  2380. enumerable: true,
  2381. get: () => _EUMPConfig,
  2382. set: _EUMPConfig_set
  2383. });
  2384. }, nullTools)
  2385. };
  2386.  
  2387. scripts['2picsun.ru'] = {
  2388. other: [
  2389. 'pics2sun.ru', '3pics-img.ru'
  2390. ],
  2391. now: () => {
  2392. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2393. }
  2394. };
  2395.  
  2396. scripts['4pda.ru'] = {
  2397. now: () => {
  2398. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2399. let isForum = location.pathname.startsWith('/forum/'),
  2400. remove = node => (node && node.parentNode.removeChild(node)),
  2401. hide = node => (node && (node.style.display = 'none'));
  2402.  
  2403. // clean a page
  2404. window.addEventListener(
  2405. 'DOMContentLoaded', function() {
  2406. let width = () => window.innerWidth || _de.clientWidth || _document.body.clientWidth || 0;
  2407. let height = () => window.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2408.  
  2409. HeaderAds: {
  2410. // hide ads above HEADER
  2411. let header = _document.querySelector('.drop-search');
  2412. if (!header) {
  2413. _console.warn('Unable to locate header element');
  2414. break HeaderAds;
  2415. }
  2416. header = header.parentNode.parentNode;
  2417. for (let itm of header.parentNode.children)
  2418. if (itm !== header)
  2419. hide(itm);
  2420. else break;
  2421. }
  2422.  
  2423. if (isForum) {
  2424. let itm = _document.querySelector('#logostrip');
  2425. if (itm)
  2426. remove(itm.parentNode.nextSibling);
  2427. // clear background in the download frame
  2428. if (location.pathname.startsWith('/forum/dl/')) {
  2429. let setBackground = node => _setAttribute(
  2430. node,
  2431. 'style', (_getAttribute(node, 'style') || '') +
  2432. ';background-color:#4ebaf6!important'
  2433. );
  2434. setBackground(_document.body);
  2435. for (let itm of _document.querySelectorAll('body > div'))
  2436. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2437. remove(itm);
  2438. else
  2439. setBackground(itm);
  2440. }
  2441. // exist from DOMContentLoaded since the rest is not for forum
  2442. return;
  2443. }
  2444.  
  2445. FixNavMenu: {
  2446. // restore DevDB link in the navigation
  2447. let itm = _document.querySelector('#nav li a[href$="/devdb/"]')
  2448. if (!itm) {
  2449. _console.warn('Unable to locate navigation menu');
  2450. break FixNavMenu;
  2451. }
  2452. itm.closest('li').style.display = 'block';
  2453. // hide ad link from the navigation
  2454. hide(_document.querySelector('#nav li a[data-dotrack]'));
  2455. }
  2456. SidebarAds: {
  2457. // remove ads from sidebar
  2458. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child');
  2459. if (!aside.length) {
  2460. _console.warn('Unable to locate sidebar');
  2461. break SidebarAds;
  2462. }
  2463. let post;
  2464. for (let side of aside) {
  2465. _console.log('Processing potential sidebar:', side);
  2466. for (let itm of Array.from(side.children)) {
  2467. post = itm.classList.contains('post');
  2468. if (itm.querySelector('iframe') && !post)
  2469. remove(itm);
  2470. if (itm.querySelector('script, a[target="_blank"] > img') && !post || !itm.children.length)
  2471. hide(itm);
  2472. }
  2473. }
  2474. }
  2475.  
  2476. _document.body.setAttribute('style', (_document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2477.  
  2478. let extra = 'background-image:none!important;background-color:transparent!important',
  2479. fakeStyles = new WeakMap(),
  2480. styleProxy = {
  2481. get: (target, prop) => fakeStyles.get(target)[prop] || target[prop],
  2482. set: function(target, prop, value) {
  2483. let fakeStyle = fakeStyles.get(target);
  2484. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2485. return true;
  2486. }
  2487. };
  2488. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2489. if (!(itm.offsetWidth > 0.95 * width() &&
  2490. itm.offsetHeight > 0.85 * height()))
  2491. continue;
  2492. if (itm.tagName !== 'A') {
  2493. fakeStyles.set(itm.style, {
  2494. 'backgroundImage': itm.style.backgroundImage,
  2495. 'backgroundColor': itm.style.backgroundColor
  2496. });
  2497.  
  2498. try {
  2499. Object.defineProperty(itm, 'style', {
  2500. value: new Proxy(itm.style, styleProxy),
  2501. enumerable: true
  2502. });
  2503. } catch (e) {
  2504. _console.log('Unable to protect style property.', e);
  2505. }
  2506.  
  2507. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2508. }
  2509. if (itm.tagName === 'A')
  2510. _setAttribute(itm, 'style', 'display:none!important');
  2511. }
  2512. }
  2513. );
  2514. }
  2515. };
  2516.  
  2517. scripts['adhands.ru'] = () => scriptLander(() => {
  2518. let nt = new nullTools();
  2519. try {
  2520. let _adv;
  2521. Object.defineProperty(win, 'adv', {
  2522. get: () => _adv,
  2523. set: (v) => {
  2524. _console.log('Blocked advert on adhands.ru.');
  2525. nt.define(v, 'advert', '');
  2526. _adv = v;
  2527. }
  2528. });
  2529. } catch (ignore) {
  2530. if (!win.adv)
  2531. _console.log('Unable to locate advert on adhands.ru.');
  2532. else {
  2533. _console.log('Blocked advert on adhands.ru.');
  2534. nt.define(win.adv, 'advert', '');
  2535. }
  2536. }
  2537. }, nullTools);
  2538.  
  2539. scripts['all-episodes.tv'] = () => {
  2540. let nt = new nullTools();
  2541. nt.define(win, 'perX1', 2);
  2542. createStyle('#advtss, #ad3, a[href*="/ad.admitad.com/"] { display:none!important }');
  2543. };
  2544.  
  2545. scripts['allhentai.ru'] = () => {
  2546. selectiveEval();
  2547. preventPopups();
  2548. scriptLander(() => {
  2549. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2550. if (!_onerror)
  2551. return;
  2552. _onerror.set = (...args) => _console.log(args[0].toString());
  2553. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2554. });
  2555. };
  2556.  
  2557. scripts['allmovie.pro'] = {
  2558. other: ['rufilmtv.org'],
  2559. dom: function() {
  2560. // pretend to be Android to make site use different played for ads
  2561. if (isSafari)
  2562. return;
  2563. Object.defineProperty(navigator, 'userAgent', {
  2564. get: function(){
  2565. 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';
  2566. },
  2567. enumerable: true
  2568. });
  2569. }
  2570. };
  2571.  
  2572. scripts['anidub-online.ru'] = {
  2573. other: ['anime.anidub.com', 'online.anidub.com'],
  2574. dom: function() {
  2575. if (win.ogonekstart1)
  2576. win.ogonekstart1 = () => _console.log("Fire in the hole!");
  2577. },
  2578. now: () => createStyle([
  2579. '.background {background: none!important;}',
  2580. '.background > script + div,'+
  2581. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2582. '{display:none!important}'
  2583. ])
  2584. };
  2585.  
  2586. scripts['audioportal.su'] = {
  2587. now: () => createStyle('#blink2 { display: none !important }'),
  2588. dom: () => {
  2589. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2590. if (!links) return;
  2591. for (let link of links)
  2592. clickme(link);
  2593. }
  2594. };
  2595.  
  2596. scripts['avito.ru'] = () => selectiveCookies('abp|bltsr|cmtchd|crookie|is_adblock');
  2597.  
  2598. scripts['di.fm'] = () => scriptLander(() => {
  2599. let log = false;
  2600. // wrap global app object to catch registration of specific modules
  2601. let _di = void 0;
  2602. Object.defineProperty(win, 'di', {
  2603. get: () => _di,
  2604. set: vl => {
  2605. if (vl === _di)
  2606. return;
  2607. log && _console.log('di =', vl);
  2608. _di = new Proxy(vl, {
  2609. set: (di, name, vl) => {
  2610. if (vl === di[name])
  2611. return true;
  2612. if (name === 'app') {
  2613. log && _console.log('di.app =', vl);
  2614. if ('module' in vl)
  2615. vl.module = new Proxy(vl.module, {
  2616. apply: (module, that, args) => {
  2617. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2618. let name = args[0];
  2619. log && _console.warn('wrap', name, 'module');
  2620. if (typeof args[1] === 'function')
  2621. args[1] = new Proxy(args[1], {
  2622. apply: (fun, that, args) => {
  2623. if (args[0]) // module object
  2624. args[0].start = () => _console.log('Skipped start of', name);
  2625. return Reflect.apply(fun, that, args);
  2626. }
  2627. });
  2628. }// else log && _console.log('loading module', args[0]);
  2629. if (args[0] === 'Modals') {
  2630. log && _console.warn('wrap', name, 'module');
  2631. if (typeof args[1] === 'function')
  2632. args[1] = new Proxy(args[1], {
  2633. apply: (fun, that, args) => {
  2634. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2635. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2636. let _commands = args[1].commands;
  2637. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2638. apply: (fun, that, args) => {
  2639. for (let name in args[0])
  2640. if (name === 'modal:streaminterrupt' ||
  2641. name === 'modal:midroll')
  2642. args[0][name] = () => _console.log('Skipped', name, 'window');
  2643. delete _commands.setHandlers;
  2644. return Reflect.apply(fun, that, args);
  2645. }
  2646. });
  2647. }
  2648. return Reflect.apply(fun, that, args);
  2649. }
  2650. });
  2651. }
  2652. return Reflect.apply(module, that, args);
  2653. }
  2654. });
  2655. }
  2656. di[name] = vl;
  2657. return true;
  2658. }
  2659. });
  2660. }
  2661. });
  2662. // don't send errorception logs
  2663. Object.defineProperty(win, 'onerror', {
  2664. set: vl => log && _console.warn('Skipped global onerror callback', vl)
  2665. });
  2666. });
  2667.  
  2668. scripts['drive2.ru'] = () => {
  2669. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2670. scriptLander(() => {
  2671. let _d2 = void 0;
  2672. Object.defineProperty(win, 'd2', {
  2673. get: () => _d2,
  2674. set: o => {
  2675. if (o === _d2)
  2676. return true;
  2677. _d2 = new Proxy(o, {
  2678. set: (tgt, prop, val) => {
  2679. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2680. val = () => null;
  2681. tgt[prop] = val;
  2682. return true;
  2683. }
  2684. });
  2685. }
  2686. });
  2687. });
  2688. };
  2689.  
  2690. scripts['echo.msk.ru'] = () => selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  2691.  
  2692. scripts['fastpic.ru'] = () => {
  2693. let nt = new nullTools();
  2694. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2695. nt.define(win, `_0x${'4955'}`, []);
  2696. };
  2697.  
  2698. scripts['fishki.net'] = () => {
  2699. scriptLander(() => {
  2700. let nt = new nullTools();
  2701. let fishki = {};
  2702. nt.define(fishki, 'adv', nt.proxy({
  2703. afterAdblockCheck: nt.func(null),
  2704. refreshFloat: nt.func(null)
  2705. }));
  2706. nt.define(fishki, 'is_adblock', false);
  2707. nt.define(win, 'fishki', fishki);
  2708. }, nullTools);
  2709. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2710. };
  2711.  
  2712. scripts['friends.in.ua'] = () => scriptLander(() => {
  2713. Object.defineProperty(win, 'need_warning', {
  2714. get: () => 0, set: () => null
  2715. });
  2716. });
  2717.  
  2718. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2719.  
  2720. scripts['hdgo.cc'] = {
  2721. other: ['46.30.43.38', 'couber.be'],
  2722. now: () => (new MutationObserver(
  2723. (ms) => {
  2724. let m, node;
  2725. for (m of ms) for (node of m.addedNodes)
  2726. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  2727. node.removeAttribute('onerror');
  2728. }
  2729. )).observe(_document.documentElement, { childList:true, subtree: true })
  2730. };
  2731.  
  2732. scripts['gismeteo.ru'] = {
  2733. other: ['gismeteo.by', 'gismeteo.kz', 'gismeteo.ua'],
  2734. now: () => {
  2735. selectiveCookies('ab_[^=]*|bltsr|redirect|_gab');
  2736. gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2737. }
  2738. };
  2739.  
  2740. scripts['hdrezka.ag'] = () => {
  2741. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2742. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2743. };
  2744.  
  2745. scripts['hqq.tv'] = () => scriptLander(() => {
  2746. // disable anti-debugging in hqq.tv player
  2747. 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);
  2748. deepWrapAPI(root => {
  2749. // skip obfuscated stuff and a few other calls
  2750. let _setInterval = root.setInterval,
  2751. _setTimeout = root.setTimeout,
  2752. _toString = root.Function.prototype.call.bind(root.Function.prototype.toString);
  2753. root.setInterval = (...args) => {
  2754. let fun = args[0];
  2755. if (fun instanceof Function) {
  2756. let text = _toString(fun),
  2757. skip = text.includes('check();') || isObfuscated(text);
  2758. _console.warn('setInterval', text, 'skip', skip);
  2759. if (skip) return -1;
  2760. }
  2761. return _setInterval.apply(this, args);
  2762. };
  2763. let wrappedST = new WeakSet();
  2764. root.setTimeout = (...args) => {
  2765. let fun = args[0];
  2766. if (fun instanceof Function) {
  2767. let text = _toString(fun),
  2768. skip = fun.name === 'check' || isObfuscated(text);
  2769. if (!wrappedST.has(fun)) {
  2770. _console.warn('setTimeout', text, 'skip', skip);
  2771. wrappedST.add(fun);
  2772. }
  2773. if (skip) return;
  2774. }
  2775. return _setTimeout.apply(this, args);
  2776. };
  2777. // skip 'debugger' call
  2778. let _eval = root.eval;
  2779. root.eval = text => {
  2780. if (typeof text === 'string' && text.includes('debugger;')) {
  2781. _console.warn('skip eval', text);
  2782. return;
  2783. }
  2784. _eval(text);
  2785. };
  2786. // Prevent RegExpt + toString trick
  2787. let _proto = void 0;
  2788. try {
  2789. _proto = root.RegExp.prototype;
  2790. } catch(ignore) {
  2791. return;
  2792. }
  2793. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  2794. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  2795. Object.defineProperty(_proto, 'toString', {
  2796. enumerable: _RE_tS.enumerable,
  2797. configurable: _RE_tS.configurable,
  2798. get: () => _RE_tSV,
  2799. set: val => _console.warn('Attempt to change toString for', this, 'with', _toString(val))
  2800. });
  2801. });
  2802. }, deepWrapAPI);
  2803.  
  2804. scripts['hideip.me'] = {
  2805. now: () => scriptLander(() => {
  2806. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  2807. let _set_innerHTML = _innerHTML.set;
  2808. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2809. let _get_innerText = _innerText.get;
  2810. let div = _document.createElement('div');
  2811. _innerHTML.set = function(...args) {
  2812. _set_innerHTML.call(div, args[0].replace('i','a'));
  2813. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2814. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this)) ) {
  2815. _console.log('Anti-Adblock killed.');
  2816. return true;
  2817. }
  2818. _set_innerHTML.apply(this, args);
  2819. };
  2820. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  2821. Object.defineProperty(win, 'adblock', {
  2822. get: () => false,
  2823. set: () => null,
  2824. enumerable: true
  2825. });
  2826. let _$ = {};
  2827. let _$_map = new WeakMap();
  2828. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2829. let _val_gOPD = _gOPD.value;
  2830. _gOPD.value = function(...args) {
  2831. let _res = _val_gOPD.apply(this, args);
  2832. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2833. delete _res.get;
  2834. delete _res.set;
  2835. _res.value = win[args[1]];
  2836. }
  2837. return _res;
  2838. };
  2839. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2840. let getJQWrap = (n) => {
  2841. let name = n;
  2842. return {
  2843. enumerable: true,
  2844. get: () => _$[name],
  2845. set: x => {
  2846. if (_$_map.has(x)) {
  2847. _$[name] = _$_map.get(x);
  2848. return true;
  2849. }
  2850. if (x === _$.$ || x === _$.jQuery) {
  2851. _$[name] = x;
  2852. return true;
  2853. }
  2854. _$[name] = new Proxy(x, {
  2855. apply: (t, o, args) => {
  2856. let _res = t.apply(o, args);
  2857. if (_$_map.has(_res.is))
  2858. _res.is = _$_map.get(_res.is);
  2859. else {
  2860. let _is = _res.is;
  2861. _res.is = function(...args) {
  2862. if (args[0] === ':hidden')
  2863. return false;
  2864. return _is.apply(this, args);
  2865. };
  2866. _$_map.set(_is, _res.is);
  2867. }
  2868. return _res;
  2869. }
  2870. });
  2871. _$_map.set(x, _$[name]);
  2872. return true;
  2873. }
  2874. };
  2875. };
  2876. Object.defineProperty(win, '$', getJQWrap('$'));
  2877. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2878. let _dP = Object.defineProperty;
  2879. Object.defineProperty = function(...args) {
  2880. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2881. return void 0;
  2882. return _dP.apply(this, args);
  2883. };
  2884. })
  2885. };
  2886.  
  2887. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2888. let nt = new nullTools();
  2889. /*jslint evil: true */ // yes, evil, I know
  2890. let _write = _document.write.bind(_document);
  2891. /*jslint evil: false */
  2892. nt.define(_document, 'write', t => {
  2893. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2894. if (id && id[1])
  2895. return _write(`<div id="${id[1]}"></div>${t}`);
  2896. return _write('');
  2897. });
  2898. });
  2899.  
  2900. scripts['imageban.ru'] = () => { Object.defineProperty(win, 'V7x1J', { get: () => null }); };
  2901.  
  2902. scripts['ivi.ru'] = () => {
  2903. let _xhr_open = win.XMLHttpRequest.prototype.open;
  2904. win.XMLHttpRequest.prototype.open = function(method, url, ...args) {
  2905. if (typeof url === 'string')
  2906. if (url.endsWith('/track'))
  2907. return;
  2908. return _xhr_open.call(this, method, url, ...args);
  2909. };
  2910. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  2911. let _responseText_get = _responseText.get;
  2912. _responseText.get = function() {
  2913. if (this.__responseText__)
  2914. return this.__responseText__;
  2915. let res = _responseText_get.apply(this, arguments);
  2916. let o;
  2917. try {
  2918. if (res)
  2919. o = JSON.parse(res);
  2920. } catch(ignore) {};
  2921. let changed = false;
  2922. if (o && o.result) {
  2923. if (o.result instanceof Array &&
  2924. 'adv_network_logo_url' in o.result[0]) {
  2925. o.result = [];
  2926. changed = true;
  2927. }
  2928. if (o.result.show_adv) {
  2929. o.result.show_adv = false;
  2930. changed = true;
  2931. }
  2932. }
  2933. if (changed) {
  2934. _console.log('changed response >>', o);
  2935. res = JSON.stringify(o);
  2936. }
  2937. this.__responseText__ = res;
  2938. return res;
  2939. };
  2940. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  2941. };
  2942.  
  2943. scripts['kinopoisk.ru'] = () => {
  2944. selectiveCookies('bltsr|cmtchd|crookie|kpunk');
  2945. // set no-branding body style and adjust other blocks on the page
  2946. let style = [
  2947. '.app__header.app__header_margin-bottom_brand, #top { margin-bottom: 20px !important }',
  2948. '.app__branding { display: none !important}'
  2949. ];
  2950. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  2951. style.push('html:not(#id), body:not(#id), .app-container { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2952. createStyle(style);
  2953. // catch branding and other things
  2954. let _KP = void 0;
  2955. Object.defineProperty(win, 'KP', {
  2956. get: () => _KP,
  2957. set: val => {
  2958. if (_KP === val)
  2959. return true;
  2960. _KP = new Proxy(val, {
  2961. set: (kp, name, val) => {
  2962. if (name === 'branding') {
  2963. kp[name] = new Proxy({ weborama: {} }, {
  2964. get: (kp, name) => name in kp ? kp[name] : '',
  2965. set: () => true
  2966. });
  2967. return true;
  2968. }
  2969. if (name === 'config')
  2970. val = new Proxy(val, {
  2971. set: (cfg, name, val) => {
  2972. if (name === 'anContextUrl')
  2973. return true;
  2974. if (name === 'adfoxEnabled' || name === 'hasBranding')
  2975. val = false;
  2976. if (name === 'adfoxVideoAdUrls')
  2977. val = {flash:{}, html:{}};
  2978. cfg[name] = val;
  2979. return true;
  2980. }
  2981. });
  2982. kp[name] = val;
  2983. return true;
  2984. }
  2985. });
  2986. _console.log('KP =', val);
  2987. }
  2988. });
  2989. // skip branding and some other junk
  2990. Object.defineProperty(win, 'advBlock', {
  2991. get: () => () => null,
  2992. set: () => true
  2993. });
  2994. // skip timeout check for blocked requests
  2995. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  2996. let _toString = Function.prototype.apply.bind(Function.prototype.toString);
  2997. win.setTimeout = function(...args) {
  2998. if (args[1] === 100) {
  2999. let str = _toString(args[0]);
  3000. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3001. return;
  3002. }
  3003. return _setTimeout(this, args);
  3004. };
  3005. };
  3006.  
  3007. scripts['kinozal-tv.appspot.com'] = {
  3008. other: ['a-dot-kinozal-tv.appspot.com'],
  3009. now: () => {
  3010. selectiveCookies('~ab');
  3011. document.cookie = 'MarketGidStorage=42';
  3012. document.cookie = '_ga=42';
  3013. }
  3014. };
  3015.  
  3016. scripts['korrespondent.net'] = {
  3017. now: () => scriptLander(() => {
  3018. let nt = new nullTools();
  3019. nt.define(win, 'holder', function(id) {
  3020. let div = _document.getElementById(id);
  3021. if (!div)
  3022. return;
  3023. if (div.parentNode.classList.contains('col__sidebar')) {
  3024. div.parentNode.appendChild(div);
  3025. div.style.height = '300px';
  3026. }
  3027. });
  3028. }, nullTools),
  3029. dom: () => {
  3030. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3031. frame.parentNode.style.width = '1px';
  3032. }
  3033. };
  3034.  
  3035. scripts['liveinternet.ru'] = () => selectiveEval(evalPatternYandex);
  3036.  
  3037. scripts['mail.ru'] = {
  3038. other: ['ok.ru'],
  3039. now: () => {
  3040. selectiveCookies('act|testcookie');
  3041. scriptLander(() => {
  3042. let nt = new nullTools();
  3043. // Trick to prevent mail.ru from removing 3rd-party styles
  3044. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  3045. // Disable some of their counters
  3046. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  3047. if (location.hostname === 'e.mail.ru')
  3048. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  3049. else
  3050. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  3051.  
  3052. {
  3053. let missingCheck = {
  3054. get: (obj, name) => {
  3055. if (!(name in obj))
  3056. _console.warn(obj, 'missing:', name);
  3057. return obj[name];
  3058. }
  3059. };
  3060. let skipLog = (name, ret) => (...args) => (_console.log(`Skip ${name}(`, ...args, ')'), ret);
  3061. let createSkipLogObject = (baseName, list) => list.reduce(
  3062. (acc, cur) => (acc[cur] = skipLog(`${baseName}.${cur}`), acc),
  3063. {}
  3064. );
  3065. let redefiner = {
  3066. apply: (target, thisArg, args) => {
  3067. let res = void 0;
  3068. if (target._name === 'mrg-smokescreen/Welter')
  3069. res = {
  3070. isWelter: () => true,
  3071. wrap: skipLog(`${target._name}.wrap`)
  3072. };
  3073. if (target._name === 'mrg-smokescreen/StyleSheets')
  3074. res = createSkipLogObject(target._name, ['update', 'remove', 'insert', 'setup']);
  3075. if (target._name === 'mrg-honeypot/main')
  3076. res = { check: skipLog(`${target._name}.check`, false) };
  3077. if (target._name.startsWith('advert/rb/slot')) {
  3078. res = createSkipLogObject(target._name, ['get', 'getHTML', 'createBlock', 'onRedirect']);
  3079. res.slot = '0';
  3080. }
  3081. if (target._name.startsWith('OK/banners/'))
  3082. res = createSkipLogObject(target._name, ['activate', 'deactivate']);
  3083. if (target._name === 'mimic') {
  3084. res = createSkipLogObject(target._name, ['insertDirect', 'setup']);
  3085. res.version = "%PACKAGE_VERSION%";
  3086. }
  3087. if (target._name === 'advert/adman/adman')
  3088. res = createSkipLogObject(target._name, ['refresh', 'getBlock', 'init']);
  3089. if (res)
  3090. res = new Proxy(res, missingCheck);
  3091. else
  3092. res = target.apply(thisArg, args);
  3093. if (target._name === 'mrg-smokescreen/Utils')
  3094. res.extend = function(...args) {
  3095. let res = {
  3096. enable: false,
  3097. match: [],
  3098. links: []
  3099. };
  3100. _console.log(`${target._name}.extend(`, ...args, ') >>', res );
  3101. return res;
  3102. };
  3103. if (target._name === 'advert/RB') {
  3104. res.getSlots = () => [];
  3105. res.load._name = target._name + '.load';
  3106. res.load = new Proxy(res.load, redefiner);
  3107. }
  3108. _console.log(target._name, '(',...args,') >>', res);
  3109. return res;
  3110. }
  3111. };
  3112.  
  3113. let wrapAdFuncs = {
  3114. apply: (target, thisArg, args) => {
  3115. let module = args[0];
  3116. if (typeof module === 'string')
  3117. if (module.startsWith('mrg-smoke') ||
  3118. module.startsWith('mrg-context') ||
  3119. module.startsWith('mrg-honeypot') ||
  3120. module.startsWith('advert') ||
  3121. module.startsWith('mimic') ||
  3122. module.startsWith('OK/banner') ||
  3123. module === 'OK/Smokescreen') {
  3124. let fun = args[args.length-1];
  3125. fun._name = module;
  3126. args[args.length-1] = new Proxy(fun, redefiner);
  3127. }// else
  3128. // _console.log('Define:', args[0]);
  3129. return target.apply(thisArg, args);
  3130. }
  3131. };
  3132. let wrapDefine = def => {
  3133. if (!def)
  3134. return;
  3135. _console.log('define =', def);
  3136. def = new Proxy(def, wrapAdFuncs);
  3137. def._name = 'define';
  3138. return def;
  3139. };
  3140. let _define = wrapDefine(win.define);
  3141. Object.defineProperty(win, 'define', {
  3142. get: () => _define,
  3143. set: x => {
  3144. if (_define === x)
  3145. return true;
  3146. _define = wrapDefine(x);
  3147. return true;
  3148. }
  3149. });
  3150. }
  3151.  
  3152. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3153. let logger = {
  3154. apply: (target, thisArg, args) => {
  3155. let res = target.apply(thisArg, args);
  3156. _console.log(`${target._name}(`, ...args, `) >>`, res);
  3157. return res;
  3158. }
  3159. };
  3160.  
  3161. let _locator;
  3162. function wrapLocator(locator) {
  3163. if ('setup' in locator) {
  3164. let _setup = locator.setup;
  3165. locator.setup = function(o) {
  3166. if ('enable' in o) {
  3167. o.enable = false;
  3168. _console.log('Disable mimic mode.');
  3169. }
  3170. if ('links' in o) {
  3171. o.links = [];
  3172. _console.log('Call with empty list of sheets.');
  3173. }
  3174. return _setup.call(this, o);
  3175. };
  3176. locator.insertSheet = () => false;
  3177. locator.wrap = () => false;
  3178. }
  3179. try {
  3180. let names = [];
  3181. for (let name in locator)
  3182. if (locator[name] instanceof Function && name !== 'transform') {
  3183. locator[name]._name = "locator." + name;
  3184. locator[name] = new Proxy(locator[name], logger);
  3185. names.push(name);
  3186. }
  3187. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3188. } catch(e) {
  3189. _console.log(e);
  3190. }
  3191. _locator = locator;
  3192. }
  3193.  
  3194. function defineLocator(root) {
  3195. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3196. if (!loc_desc || loc_desc.set !== wrapLocator)
  3197. try {
  3198. Object.defineProperty(root, 'locator', {
  3199. set: wrapLocator,
  3200. get: () => _locator
  3201. });
  3202. } catch (err) {
  3203. _console.log('Unable to redefine "locator" object!!!', err);
  3204. }
  3205. }
  3206.  
  3207. let _honeyPot;
  3208. function defineDetector(mr) {
  3209. let __ = mr._ || {};
  3210. let setHoneyPot = o => {
  3211. if (!o || o === _honeyPot) return;
  3212. _console.log('[honeyPot]', o);
  3213. _honeyPot = function() {
  3214. this.check = new Proxy(() => {
  3215. __.STUCK_IN_POT = false;
  3216. return false;
  3217. }, logger);
  3218. this.check._name = 'honeyPot.check';
  3219. this.destroy = () => null;
  3220. };
  3221. };
  3222. if ('honeyPot' in mr)
  3223. setHoneyPot(mr.honeyPot);
  3224. else
  3225. Object.defineProperty(mr, 'honeyPot', {
  3226. get: () => _honeyPot,
  3227. set: setHoneyPot
  3228. });
  3229.  
  3230. __ = new Proxy(__, {
  3231. get: (t, p) => t[p],
  3232. set: (t, p, v) => {
  3233. _console.log(`mr._.${p} =`, v);
  3234. t[p] = v;
  3235. return true;
  3236. }
  3237. });
  3238. mr._ = __;
  3239. }
  3240.  
  3241. function defineAdd(mr) {
  3242. let _add;
  3243. let addWrapper = {
  3244. apply: (tgt, that, args) => {
  3245. let module = args[0];
  3246. if (typeof module === 'string' && module.startsWith('ad')) {
  3247. _console.log('Skip module:', module);
  3248. return;
  3249. }
  3250. if (typeof module === 'object' && module.name.startsWith('ad'))
  3251. _console.log('Loaded module:', module);
  3252. return logger.apply(tgt, that, args);
  3253. }
  3254. };
  3255. let setMrAdd = v => {
  3256. if (!v) return;
  3257. v._name = 'mr.add';
  3258. v = new Proxy(v, addWrapper);
  3259. _add = v;
  3260. };
  3261. if ('add' in mr)
  3262. setMrAdd(mr.add);
  3263. Object.defineProperty(mr, 'add', {
  3264. get: () => _add,
  3265. set: setMrAdd
  3266. });
  3267.  
  3268. }
  3269.  
  3270. let _mr_wrapper = vl => {
  3271. defineLocator(vl.mimic ? vl.mimic : vl);
  3272. defineDetector(vl);
  3273. defineAdd(vl);
  3274. return vl;
  3275. };
  3276. if ('mr' in win) {
  3277. _console.log('Found existing "mr" object.');
  3278. win.mr = _mr_wrapper(win.mr);
  3279. } else {
  3280. let _mr = void 0;
  3281. Object.defineProperty(win, 'mr', {
  3282. get: () => _mr,
  3283. set: vl => { _mr = _mr_wrapper(vl) },
  3284. configurable: true
  3285. });
  3286. let _defineProperty = Function.prototype.apply.bind(Object.defineProperty);
  3287. Object.defineProperty = function defineProperty(o, name, conf) {
  3288. if (name === 'mr' && o instanceof Window) {
  3289. _console.warn('Object.defineProperty(', ...arguments, ')');
  3290. conf.set(_mr_wrapper(conf.get()));
  3291. }
  3292. if ((name === 'honeyPot' || name === 'add') && _mr === o && conf.set)
  3293. return;
  3294. return _defineProperty(this, arguments);
  3295. };
  3296. }
  3297.  
  3298. // smokyTools wrapper for news.mail.ru
  3299. nt.define(win, 'smokyTools', nt.proxy({
  3300. getDict: nt.func(nt.proxy({}, 'smokyTools.getDict', null), 'smokyTools.getDict'),
  3301. CSS: nt.func(nt.proxy({}, 'smokyTools.CSS', null), 'smokyTools.CSS')
  3302. }, 'smokyTools', null));
  3303. nt.define(win, 'smoky', nt.func(null, 'smoky'));
  3304. nt.define(win, 'smokySingleElement', nt.func(null, 'smokySingleElement'));
  3305. nt.define(win, 'smokyByClass', nt.func(null, 'smokyByClass'));
  3306. }, nullTools);
  3307. }
  3308. };
  3309.  
  3310. scripts['oms.matchat.online'] = () => scriptLander(() => {
  3311. let _rmpGlobals = void 0;
  3312. Object.defineProperty(win, 'rmpGlobals', {
  3313. get: () => _rmpGlobals,
  3314. set: x => {
  3315. if (x === _rmpGlobals)
  3316. return true;
  3317. _rmpGlobals = new Proxy(x, {
  3318. get: (obj, name) => {
  3319. if (name === 'adBlockerDetected')
  3320. return false;
  3321. return obj[name];
  3322. },
  3323. set: (obj, name, val) => {
  3324. if (name === 'adBlockerDetected')
  3325. _console.warn('rmpGlobals.adBlockerDetected =', val)
  3326. else
  3327. obj[name] = val;
  3328. return true;
  3329. }
  3330. });
  3331. }
  3332. });
  3333. });
  3334.  
  3335. scripts['megogo.net'] = {
  3336. now: () => {
  3337. let nt = new nullTools();
  3338. nt.define(win, 'adBlock', false);
  3339. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3340. }
  3341. };
  3342.  
  3343. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3344.  
  3345. scripts['newdeaf-online.net'] = {
  3346. dom: () => {
  3347. let adNodes = _document.querySelectorAll('.ads');
  3348. if (!adNodes)
  3349. return;
  3350. let getter = x => {
  3351. let val = x;
  3352. return () => (_console.warn('read .ads', name, val), val);
  3353. };
  3354. let setter = x => _console.warn('skip write .ads', name, x);
  3355. for (let adNode of adNodes)
  3356. for (let name of ['innerHTML'])
  3357. Object.defineProperty(adNode, name, {
  3358. get: getter(ads[name]),
  3359. set: setter
  3360. });
  3361. }
  3362. };
  3363.  
  3364. scripts['overclockers.ru'] = {
  3365. dom: () => scriptLander(() => {
  3366. let killed = () => _console.warn('Anti-Adblock killed.');
  3367. if ('$' in win)
  3368. win.$ = new Proxy($, {
  3369. apply: (tgt, that, args) => {
  3370. let res = tgt.apply(that, args);
  3371. if (res[0] && res[0] === _document.body) {
  3372. res.html = killed;
  3373. res.empty = killed;
  3374. }
  3375. return res;
  3376. }
  3377. });
  3378. })
  3379. };
  3380. scripts['forums.overclockers.ru'] = {
  3381. now: () => {
  3382. createStyle('.needblock {position: fixed; left: -10000px}');
  3383. Object.defineProperty(win, 'adblck', {
  3384. get: () => 'no',
  3385. set: () => undefined,
  3386. enumerable: true
  3387. });
  3388. }
  3389. };
  3390.  
  3391. scripts['pb.wtf'] = {
  3392. other: ['piratbit.org', 'piratbit.ru'],
  3393. dom: () => {
  3394. // line above topic content and images in the slider in the header
  3395. let remove = node => (_console.log('removed', node), node.parentNode.removeChild(node));
  3396. for (let el of _document.querySelectorAll('.release-block-img a, #page_content a')) {
  3397. if (location.hostname === el.hostname &&
  3398. /^\/(\w{3}|exit)\/[\w=/]{20,}$/.test(el.pathname)) {
  3399. remove(el.closest('div, tr'));
  3400. continue;
  3401. }
  3402. // ads in the topic header in case filter above wasn't enough
  3403. let parent = el.closest('tr');
  3404. if (parent) {
  3405. let span = (parent.querySelector('span') || {}).textContent;
  3406. span && span.startsWith('YO!') && remove(parent);
  3407. }
  3408. }
  3409. // casino ad button in random places
  3410. for (let el of _document.querySelectorAll('.btn-group')) {
  3411. el = el.parentNode;
  3412. if (el.tagName === 'CENTER')
  3413. remove(el.parentNode);
  3414. }
  3415. // ads in comments
  3416. let el = _document.querySelector('thead + tbody[id^="post_"] + tbody[class*=" "]');
  3417. if (el && el.parentNode.children[2] == el)
  3418. remove(el);
  3419. }
  3420. };
  3421.  
  3422. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3423.  
  3424. scripts['peka2.tv'] = () => {
  3425. let bodyClass = 'body--branding';
  3426. let checkNode = node => {
  3427. for (let className of node.classList)
  3428. if (className.includes('banner') || className === bodyClass) {
  3429. _removeAttribute(node, 'style');
  3430. node.classList.remove(className);
  3431. for (let attr of Array.from(node.attributes))
  3432. if (attr.name.startsWith('advert'))
  3433. _removeAttribute(node, attr.name);
  3434. }
  3435. };
  3436. (new MutationObserver(ms => {
  3437. let m, node;
  3438. for (m of ms) for (node of m.addedNodes)
  3439. if (node instanceof HTMLElement)
  3440. checkNode(node);
  3441. })).observe(_de, {childList: true, subtree: true});
  3442. (new MutationObserver(ms => {
  3443. for (let m of ms)
  3444. checkNode(m.target);
  3445. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3446. };
  3447.  
  3448. scripts['qrz.ru'] = {
  3449. now: () => {
  3450. let nt = new nullTools();
  3451. nt.define(win, 'ab', false);
  3452. nt.define(win, 'tryMessage', nt.func(null));
  3453. }
  3454. };
  3455.  
  3456. scripts['razlozhi.ru'] = {
  3457. now: () => {
  3458. let nt = new nullTools();
  3459. nt.define(win, 'cadb', false);
  3460. for (let func of ['createShadowRoot', 'attachShadow'])
  3461. if (func in _Element)
  3462. _Element[func] = function(){
  3463. return this.cloneNode();
  3464. };
  3465. }
  3466. };
  3467.  
  3468. scripts['rbc.ru'] = {
  3469. other: ['autonews.ru', 'rbcplus.ru', 'sportrbc.ru'],
  3470. now: () => {
  3471. selectiveCookies('adb_on');
  3472. let _RA = void 0;
  3473. let setArgs = {
  3474. 'showBanners': true,
  3475. 'showAds': true,
  3476. 'banners.staticPath': '',
  3477. 'paywall.staticPath': '',
  3478. 'banners.dfp.config': [],
  3479. 'banners.dfp.pageTargeting': () => null,
  3480. };
  3481. Object.defineProperty(win, 'RA', {
  3482. get: () => _RA,
  3483. set: vl => {
  3484. _console.log('RA =', vl);
  3485. if ('repo' in vl) {
  3486. _console.log('RA.repo =', vl.repo);
  3487. vl.repo = new Proxy(vl.repo, {
  3488. set: (o, name, val) => {
  3489. if (name === 'banner') {
  3490. _console.log(`RA.repo.${name} =`, val);
  3491. val = new Proxy(val, {
  3492. get: (o, name) => {
  3493. let res = o[name];
  3494. if (typeof o[name] === 'function') {
  3495. res = () => null;
  3496. res.toString = o[name].toString.bind(o[name]);
  3497. }
  3498. if (name === 'isInited')
  3499. res = true;
  3500. _console.warn(`get RA.repo.banner.${name}`, res);
  3501. return res;
  3502. }
  3503. });
  3504. }
  3505. o[name] = val;
  3506. return true;
  3507. }
  3508. });
  3509. } else
  3510. _console.log('Unable to locate RA.repo');
  3511. _RA = new Proxy(vl, {
  3512. set: (o, name, val) => {
  3513. if (name === 'config') {
  3514. _console.log('RA.config =', val);
  3515. if ('set' in val) {
  3516. val.set = new Proxy(val.set, {
  3517. apply: (set, that, args) => {
  3518. let name = args[0];
  3519. if (name in setArgs)
  3520. args[1] = setArgs[name];
  3521. if (name in setArgs || name === 'checkad')
  3522. _console.log('RA.config.set(', ...args, ')');
  3523. return Reflect.apply(set, that, args);
  3524. }
  3525. });
  3526. val.set('showAds', true); // pretend ads already were shown
  3527. }
  3528. }
  3529. o[name] = val;
  3530. return true;
  3531. }
  3532. });
  3533. }
  3534. });
  3535. Object.defineProperty(win, 'bannersConfig', {
  3536. get: () => [], set: () => null
  3537. });
  3538. // pretend there is a paywall landing on screen already
  3539. let pwl = _document.createElement('div');
  3540. pwl.style.display = 'none';
  3541. pwl.className = 'js-paywall-landing';
  3542. _document.documentElement.appendChild(pwl);
  3543. // detect and skip execution of one of the ABP detectors
  3544. let _setTimeout = Function.prototype.apply.bind(win.setTimeout);
  3545. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3546. win.setTimeout = function setTimeout() {
  3547. if (typeof arguments[0] === 'function') {
  3548. let fts = _toString(arguments[0]);
  3549. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  3550. _console.log('Skipped setTimout(', fts, arguments[1], ')');
  3551. return;
  3552. }
  3553. }
  3554. return _setTimeout(this, arguments);
  3555. };
  3556. // hide banner placeholders
  3557. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  3558. },
  3559. dom: () => {
  3560. // hide sticky banner place at the top of the page
  3561. for (let itm of _document.querySelectorAll('.l-sticky'))
  3562. if (itm.querySelector('.banner__container__link'))
  3563. itm.style.display = 'none';
  3564. }
  3565. };
  3566.  
  3567. scripts['rp5.ru'] = {
  3568. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3569. now: () => {
  3570. Object.defineProperty(win, 'sContentBottom', {
  3571. get: () => '',
  3572. set: () => true
  3573. });
  3574. },
  3575. dom: () => {
  3576. let node = selectNodeByTextContent('Разместить текстовое объявление', { root: _de.querySelector('#content-wrapper'), shallow: true });
  3577. if (node)
  3578. node.style.display = 'none';
  3579. }
  3580. };
  3581.  
  3582. scripts['rutube.ru'] = () => scriptLander(() => {
  3583. let _parse = JSON.parse;
  3584. let _skip_enabled = false;
  3585. JSON.parse = (...args) => {
  3586. let res = _parse(...args),
  3587. log = false;
  3588. if (!res)
  3589. return res;
  3590. // parse player configuration
  3591. if ('appearance' in res || 'video_balancer' in res) {
  3592. log = true;
  3593. if (res.appearance) {
  3594. if ('forbid_seek' in res.appearance && res.appearance.forbid_seek)
  3595. res.appearance.forbid_seek = false;
  3596. if ('forbid_timeline_preview' in res.appearance && res.appearance.forbid_timeline_preview)
  3597. res.appearance.forbid_timeline_preview = false;
  3598. }
  3599. _skip_enabled = !!res.remove_unseekable_blocks;
  3600. //res.advert = [];
  3601. delete res.advert;
  3602. //for (let limit of res.limits)
  3603. // limit.limit = 0;
  3604. delete res.limits;
  3605. //res.yast = null;
  3606. //res.yast_live_online = null;
  3607. delete res.yast;
  3608. delete res.yast_live_online;
  3609. Object.defineProperty(res, 'stat', {
  3610. get: () => [],
  3611. set: () => true,
  3612. enumerable: true
  3613. });
  3614. }
  3615.  
  3616. // parse video configuration
  3617. if ('video_url' in res) {
  3618. log = true;
  3619. if (res.cuepoints && !_skip_enabled)
  3620. for (let point of res.cuepoints) {
  3621. point.is_pause = false;
  3622. point.show_navigation = true;
  3623. point.forbid_seek = false;
  3624. }
  3625. }
  3626.  
  3627. if (log)
  3628. _console.log('[rutube]', res);
  3629. return res;
  3630. };
  3631. });
  3632.  
  3633. scripts['simpsonsua.com.ua'] = () => scriptLander(() => {
  3634. let _addEventListener = _Document.addEventListener;
  3635. _document.addEventListener = function(event, callback) {
  3636. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  3637. return;
  3638. return _addEventListener.apply(this, arguments);
  3639. };
  3640. });
  3641.  
  3642. scripts['smotretanime.ru'] = () => scriptLander(() => {
  3643. deepWrapAPI(root => {
  3644. let _pause = root.Function.prototype.call.bind(root.Audio.prototype.pause);
  3645. let _addEventListener = root.Function.prototype.call.bind(root.Element.prototype.addEventListener);
  3646. let stopper = e => _pause(e.target);
  3647. root.Audio = new Proxy(root.Audio, {
  3648. construct: (audio, args) => {
  3649. let res = new audio(...args);
  3650. _addEventListener(res, 'play', stopper, true);
  3651. return res;
  3652. }
  3653. });
  3654. _createElement = root.Document.prototype.createElement;
  3655. root.Document.prototype.createElement = function createElement() {
  3656. let res = _createElement.apply(this, arguments);
  3657. if (res instanceof HTMLAudioElement)
  3658. _addEventListener(res, 'play', stopper, true);
  3659. return res;
  3660. };
  3661. });
  3662. }, deepWrapAPI);
  3663.  
  3664. scripts['spaces.ru'] = () => {
  3665. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3666. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3667. };
  3668.  
  3669. scripts['spam-club.blogspot.co.uk'] = () => {
  3670. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  3671. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  3672. let wrapGetter = (getter) => {
  3673. let _getter = getter;
  3674. return function() {
  3675. let _size = _getter.apply(this, arguments);
  3676. return _size ? _size : 1;
  3677. };
  3678. };
  3679. _clientHeight.get = wrapGetter(_clientHeight.get);
  3680. _clientWidth.get = wrapGetter(_clientWidth.get);
  3681. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  3682. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  3683. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3684. _set_onload = _onload.set;
  3685. _onload.set = function() {
  3686. if (this instanceof HTMLImageElement)
  3687. return true;
  3688. _set_onload.apply(this, arguments);
  3689. };
  3690. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3691. };
  3692.  
  3693. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3694.  
  3695. scripts['sports.ru'] = {
  3696. now: () => {
  3697. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3698. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3699. // extra functionality: shows/hides panel at the top depending on scroll direction
  3700. createStyle([
  3701. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3702. '.user-panel-up { top: -40px!important }'
  3703. ], {id: 'userPanelSlide'}, false);
  3704. },
  3705. dom: () => {
  3706. (function lookForPanel() {
  3707. let panel = _document.querySelector('.user-panel__fixed');
  3708. if (!panel)
  3709. setTimeout(lookForPanel, 100);
  3710. else
  3711. window.addEventListener(
  3712. 'wheel', function(e) {
  3713. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3714. panel.classList.add('user-panel-up');
  3715. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3716. panel.classList.remove('user-panel-up');
  3717. }, false
  3718. );
  3719. })();
  3720. }
  3721. };
  3722.  
  3723. scripts['stealthz.ru'] = {
  3724. dom: () => {
  3725. // skip timeout
  3726. let $ = _document.querySelector.bind(_document);
  3727. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3728. if (!timer_1 || !timer_2)
  3729. return;
  3730. timer_1.style.display = 'none';
  3731. timer_2.style.display = 'block';
  3732. }
  3733. };
  3734.  
  3735. scripts['xittv.net'] = () => scriptLander(() => {
  3736. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  3737. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  3738. let _jwplayer = void 0;
  3739. Object.defineProperty(win, 'jwplayer', {
  3740. get: () => _jwplayer,
  3741. set: x => {
  3742. _jwplayer = new Proxy(x, {
  3743. apply: (fun, that, args) => {
  3744. let res = fun.apply(that, args);
  3745. res = new Proxy(res, {
  3746. get: (obj, name) => {
  3747. if (logNames.includes(name) && obj[name] instanceof Function)
  3748. return new Proxy(obj[name], {
  3749. apply: (fun, that, args) => {
  3750. if (name === 'setup') {
  3751. let o = args[0];
  3752. if (o)
  3753. delete o.advertising;
  3754. }
  3755. if (name === 'on' || name === 'trigger') {
  3756. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  3757. if (events.length === 1 && skipEvents.includes(events[0]))
  3758. return res;
  3759. if (events.length > 1) {
  3760. let names = [];
  3761. for (let event of events)
  3762. if (!skipEvents.includes(event))
  3763. names.push(event);
  3764. if (names.length > 0)
  3765. args[0] = names.join(" ");
  3766. else
  3767. return res;
  3768. }
  3769. }
  3770. let subres = fun.apply(that, args);
  3771. _console.warn(`jwplayer().${name}(`, ...args, `) >>`, res);
  3772. return subres;
  3773. }
  3774. });
  3775. return obj[name];
  3776. }
  3777. });
  3778. return res;
  3779. }
  3780. });
  3781. _console.log('jwplayer =', x);
  3782. }
  3783. });
  3784. });
  3785.  
  3786. scripts['yap.ru'] = {
  3787. other: ['yaplakal.com'],
  3788. now: () => {
  3789. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3790. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3791. }
  3792. };
  3793.  
  3794. scripts['rambler.ru'] = {
  3795. other: ['championat.com', 'gazeta.ru', 'lenta.ru', 'media.eagleplatform.com', 'quto.ru', 'rns.online'],
  3796. now: () => {
  3797. selectiveCookies('detect_count');
  3798. scriptLander(() => {
  3799. // Prevent autoplay
  3800. if (!('EaglePlayer' in win)) {
  3801. let _EaglePlayer = void 0;
  3802. Object.defineProperty(win, 'EaglePlayer', {
  3803. enumerable: true,
  3804. get: () => _EaglePlayer,
  3805. set: x => {
  3806. if (x === _EaglePlayer)
  3807. return true;
  3808. _EaglePlayer = new Proxy(x, {
  3809. construct: (targ, args) => {
  3810. let player = new targ(...args);
  3811. if (!player.options) {
  3812. _console.log('EaglePlayer: no options', EaglePlayer);
  3813. return player;
  3814. }
  3815. Object.defineProperty(player.options, 'autoplay', {
  3816. get: () => false,
  3817. set: () => true
  3818. });
  3819. Object.defineProperty(player.options, 'scroll', {
  3820. get: () => false,
  3821. set: () => true
  3822. });
  3823. return player;
  3824. }
  3825. });
  3826. }
  3827. });
  3828. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3829. let isAutoplay = /^autoplay$/i;
  3830. _Element.setAttribute = function setAttribute(name) {
  3831. if (!this._stopped && isAutoplay.test(name)) {
  3832. _console.log('Prevented assigning autoplay attribute.');
  3833. return null;
  3834. }
  3835. return _setAttribute(this, arguments);
  3836. };
  3837. } else {
  3838. _console.log('EaglePlayer function already exists.');
  3839. if (inIFrame) {
  3840. let _setAttribute = Function.prototype.apply.bind(_Element.setAttribute);
  3841. let isAutoplay = /^autoplay$/i;
  3842. _Element.setAttribute = function setAttribute(name) {
  3843. if (!this._stopped && isAutoplay.test(name)) {
  3844. _console.log('Prevented assigning autoplay attribute.');
  3845. this._stopped = true;
  3846. this.play = () => {
  3847. _console.log('Prevented attempt to force-start playback.');
  3848. delete this.play;
  3849. };
  3850. return null;
  3851. }
  3852. return _setAttribute(this, arguments);
  3853. };
  3854. }
  3855. }
  3856. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3857. return;
  3858. let nt = new nullTools();
  3859. // Adblock Detector
  3860. let _hidden = void 0;
  3861. Object.defineProperty(win, 'QW50aS1BZEJsb2Nr', {
  3862. set: vl => {
  3863. for (let name in vl) delete vl[name];
  3864. nt.define(vl, 'Detector', nt.proxy({
  3865. getBlockingStatus: () => new Promise(),
  3866. blockingDetectors: [],
  3867. baitURLPrefix: '',
  3868. commonRules: []
  3869. }));
  3870. nt.define(vl, 'isAdBlockFlag', '');
  3871. nt.define(vl, 'ruid', '');
  3872. nt.define(vl, 'user', nt.proxy({
  3873. getOrSetUid: () => null
  3874. }));
  3875. _console.log('Found Adblock Detector.');
  3876. _hidden = vl;
  3877. },
  3878. get: () => _hidden
  3879. });
  3880. // prevent ads from loading
  3881. let blockObfuscated = false;
  3882. let obfuscation = /\[[a-z]{4}\("0x\d+"\)\]/i;
  3883. let _toString = Function.prototype.call.bind(Function.prototype.toString);
  3884. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3885. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3886. let _cssText_get = _cssText.get;
  3887. _cssText.configurable = false;
  3888. _cssText.get = function() {
  3889. let cssText = _cssText_get.call(this);
  3890. if (cssText.includes('content:')) {
  3891. _console.warn('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3892. blockObfuscated = true;
  3893. return null;
  3894. }
  3895. return cssText;
  3896. };
  3897. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3898. let _setTimeout = win.setTimeout;
  3899. win.setTimeout = function(f) {
  3900. if (blockObfuscated && obfuscation.test(_toString(f))) {
  3901. _console.warn('Stopped setTimeout for:', _toString(f).slice(0,100), '\u2026');
  3902. return null;
  3903. };
  3904. return _setTimeout.apply(this, arguments);
  3905. };
  3906. // fake global Adf object
  3907. let Adf_banner = {};
  3908. [
  3909. 'reloadssp', 'sspScroll',
  3910. 'sspRich', 'ssp'
  3911. ].forEach(name => void(Adf_banner[name] = nt.proxy(() => new Promise(r => r({status: true})))));
  3912. nt.define(win, 'Adf', nt.proxy({
  3913. banner: nt.proxy(Adf_banner)
  3914. }));
  3915. // extra script to remove partner news on gazeta.ru
  3916. if (!location.hostname.includes('gazeta.ru'))
  3917. return;
  3918. (new MutationObserver(
  3919. (ms) => {
  3920. let m, node, header;
  3921. for (m of ms) for (node of m.addedNodes)
  3922. if (node instanceof HTMLDivElement && node.matches('.sausage')) {
  3923. header = node.querySelector('.sausage-header');
  3924. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3925. node.style.display = 'none';
  3926. }
  3927. }
  3928. )).observe(_document.documentElement, { childList:true, subtree: true });
  3929. }, `let inIFrame = ${inIFrame}`, nullTools)
  3930. }
  3931. };
  3932.  
  3933. scripts['reactor.cc'] = {
  3934. other: ['joyreactor.cc', 'pornreactor.cc'],
  3935. now: () => {
  3936. selectiveEval();
  3937. scriptLander(() => {
  3938. let nt = new nullTools();
  3939. win.open = function(){
  3940. throw new Error('Redirect prevention.');
  3941. };
  3942. nt.define(win, 'Worker', function(){});
  3943. nt.define(win, 'JRCH', win.CoinHive);
  3944. }, nullTools);
  3945. },
  3946. click: function(e) {
  3947. let node = e.target;
  3948. if (node.nodeType === _Node.ELEMENT_NODE &&
  3949. node.style.position === 'absolute' &&
  3950. node.style.zIndex > 0)
  3951. node.parentNode.removeChild(node);
  3952. },
  3953. dom: function() {
  3954. let tid = void 0;
  3955. function probe() {
  3956. let node = selectNodeByTextContent('блокировщик рекламы');
  3957. if (!node) return;
  3958. while (node.parentNode.offsetHeight < 750 && node !== _document.body)
  3959. node = node.parentNode;
  3960. _setAttribute(node, 'style', 'background:none!important');
  3961. // stop observer
  3962. if (!tid) tid = setTimeout(() => this.disconnect(), 1000);
  3963. }
  3964. (new MutationObserver(probe))
  3965. .observe(_document, { childList:true, subtree:true });
  3966. }
  3967. };
  3968.  
  3969. scripts['auto.ru'] = () => {
  3970. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3971. let userAdsListAds = (
  3972. '.listing-list > .listing-item,'+
  3973. '.listing-item_type_fixed.listing-item'
  3974. );
  3975. let catalogAds = (
  3976. 'div[class*="layout_catalog-inline"],'+
  3977. 'div[class$="layout_horizontal"]'
  3978. );
  3979. let otherAds = (
  3980. '.advt_auto,'+
  3981. '.sidebar-block,'+
  3982. '.pager-listing + div[class],'+
  3983. '.card > div[class][style],'+
  3984. '.sidebar > div[class],'+
  3985. '.main-page__section + div[class],'+
  3986. '.listing > tbody'
  3987. );
  3988. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3989. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3990. gardener(otherAds, words);
  3991. };
  3992.  
  3993. scripts['rsload.net'] = {
  3994. load: () => {
  3995. let dis = _document.querySelector('label[class*="cb-disable"]');
  3996. if (dis)
  3997. dis.click();
  3998. },
  3999. click: e => {
  4000. let t = e.target;
  4001. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4002. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  4003. }
  4004. };
  4005.  
  4006. let domain;
  4007. // add alternative domain names if present and wrap functions into objects
  4008. for (let name in scripts) {
  4009. if (scripts[name] instanceof Function)
  4010. scripts[name] = { now: scripts[name] };
  4011. for (domain of (scripts[name].other||[])) {
  4012. if (domain in scripts)
  4013. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  4014. scripts[domain] = scripts[name];
  4015. }
  4016. delete scripts[name].other;
  4017. }
  4018. // look for current domain in the list and run appropriate code
  4019. domain = _document.domain;
  4020. while (domain.includes('.')) {
  4021. if (domain in scripts) for (let when in scripts[domain])
  4022. switch(when) {
  4023. case 'now':
  4024. scripts[domain][when]();
  4025. break;
  4026. case 'dom':
  4027. _document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  4028. break;
  4029. default:
  4030. _document.addEventListener (when, scripts[domain][when], false);
  4031. }
  4032. domain = domain.slice(domain.indexOf('.') + 1);
  4033. }
  4034.  
  4035. // Batch script lander
  4036. if (!skipLander)
  4037. landScript(batchLand, batchPrepend);
  4038.  
  4039. { // JS Fixes Tools Menu
  4040. let openOptions = function() {
  4041. let ovl = _createElement('div'),
  4042. inner = _createElement('div');
  4043. ovl.style = (
  4044. 'position: fixed;'+
  4045. 'top:0; left:0;'+
  4046. 'bottom: 0; right: 0;'+
  4047. 'background: rgba(0,0,0,0.85);'+
  4048. 'z-index: 2147483647;'+
  4049. 'padding: 5em'
  4050. );
  4051. inner.style = (
  4052. 'background: whitesmoke;'+
  4053. 'font-size: 10pt;'+
  4054. 'color: black;'+
  4055. 'padding: 1em'
  4056. );
  4057. inner.textContent = 'JS Fixes Tools';
  4058. inner.appendChild(_createElement('br'));
  4059. inner.appendChild(_createElement('br'));
  4060. ovl.addEventListener(
  4061. 'click', function(e) {
  4062. if (e.target === ovl) {
  4063. ovl.parentNode.removeChild(ovl);
  4064. e.preventDefault();
  4065. }
  4066. e.stopPropagation();
  4067. }, false
  4068. );
  4069.  
  4070. let sObjBtn = _createElement('button');
  4071. sObjBtn.onclick = getStrangeObjectsList;
  4072. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  4073. inner.appendChild(_createElement('br'));
  4074. inner.appendChild(sObjBtn);
  4075.  
  4076. _document.body.appendChild(ovl);
  4077. ovl.appendChild(inner);
  4078. };
  4079.  
  4080. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  4081. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  4082. _document.addEventListener(
  4083. 'keydown', function(e) {
  4084. if ((e.code === opKey[opPos] || e.location) &&
  4085. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey)) {
  4086. opPos += e.location ? 0 : 1;
  4087. e.stopPropagation();
  4088. e.preventDefault();
  4089. } else
  4090. opPos = 0;
  4091. if (opPos === opKey.length) {
  4092. opPos = 0;
  4093. openOptions();
  4094. }
  4095. }, false
  4096. );
  4097. }
  4098. })();