RU AdList JS Fixes

try to take over the world!

当前为 2018-12-26 提交的版本,查看 最新版本

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