RU AdList JS Fixes

try to take over the world!

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

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