RU AdList JS Fixes

try to take over the world!

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

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