RU AdList JS Fixes

try to take over the world!

当前为 2020-08-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20200823.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 *://*.telegram.org/*
  14. // @exclude *://telegram.org/*
  15. // @exclude *://trust.yandex.ru/*
  16. // @exclude *://diehard.yandex.ru/*
  17. // @exclude *://money.yandex.ru/*
  18. // @exclude *://beru.ru/*
  19. // @exclude *://*.ingress.com/*
  20. // @exclude *://hd.kinopoisk.ru/*
  21. // @grant GM_getValue
  22. // @grant GM_setValue
  23. // @grant GM_listValues
  24. // @grant GM_registerMenuCommand
  25. // @grant GM.cookie
  26. // @grant unsafeWindow
  27. // @grant window.close
  28. // @run-at document-start
  29. // ==/UserScript==
  30.  
  31. // jshint esversion: 8
  32. // jshint unused: true
  33. (function () {
  34. 'use strict';
  35.  
  36. const win = (unsafeWindow || window);
  37.  
  38. // MooTools are crazy enough to replace standard browser object window.Document: https://mootools.net/core
  39. // Occasionally their code runs before my script on some domains and causes all kinds of havoc.
  40. const
  41. _Document = Object.getPrototypeOf(HTMLDocument.prototype),
  42. _Element = Object.getPrototypeOf(HTMLElement.prototype);
  43. // dTree 2.05 in some cases replaces Node object
  44. const
  45. _Node = Object.getPrototypeOf(_Element);
  46.  
  47. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  48. const
  49. // isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  50. // isChrome = !!window.chrome && !!window.chrome.webstore,
  51. isSafari =
  52. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  53. (function (p) {
  54. return p.toString() === "[object SafariRemoteNotification]";
  55. })(!window.safari || window.safari.pushNotification),
  56. isFirefox = 'InstallTrigger' in win,
  57. inIFrame = (win.self !== win.top);
  58. const
  59. _bindCall = fun => Function.prototype.call.bind(fun),
  60. _getAttribute = _bindCall(_Element.getAttribute),
  61. _setAttribute = _bindCall(_Element.setAttribute),
  62. _removeAttribute = _bindCall(_Element.removeAttribute),
  63. _hasOwnProperty = _bindCall(Object.prototype.hasOwnProperty),
  64. _toString = _bindCall(Function.prototype.toString),
  65. _document = win.document,
  66. _de = _document.documentElement,
  67. _appendChild = _Document.appendChild.bind(_de),
  68. _removeChild = _Document.removeChild.bind(_de),
  69. _createElement = _Document.createElement.bind(_document),
  70. _querySelector = _Document.querySelector.bind(_document),
  71. _querySelectorAll = _Document.querySelectorAll.bind(_document),
  72. _attachShadow = ('attachShadow' in _Element) ? _bindCall(_Element.attachShadow) : null,
  73. _apply = Reflect.apply,
  74. _construct = Reflect.construct;
  75.  
  76. let skipLander = true;
  77. try {
  78. skipLander = !(isFirefox && 'StopIteration' in win);
  79. } catch (ignore) {}
  80.  
  81. const _console = {};
  82. _console.initConsole = () => {
  83. for (let name in win.console)
  84. _console[name] = console[name];
  85. _console._trace = _console.trace;
  86. _console.trace = (...args) => {
  87. if (!skipLander)
  88. return _console.warn(...args);
  89. _console.groupCollapsed(...args);
  90. _console._trace('Stack trace.');
  91. _console.groupEnd();
  92. };
  93. Object.freeze(_console);
  94. Object.defineProperty(win.console, 'clear', {
  95. value() {
  96. return null;
  97. }
  98. });
  99. };
  100. _console.initConsole();
  101.  
  102. const jsf = (function () {
  103. const opts = {};
  104. let getValue = (a, b) => b,
  105. setValue = () => null,
  106. listValues = () => [];
  107. try {
  108. [getValue, setValue, listValues] = [GM_getValue, GM_setValue, GM_listValues];
  109. } catch (ignore) {}
  110. // defaults
  111. opts.Lang = 'rus';
  112. opts.AbortExecutionStatistics = false;
  113. opts.AccessStatistics = false;
  114. opts.BlockNotificationPermissionRequests = false;
  115. opts.ShowScriptHandlerCompatibilityWarning = true;
  116. // load actual values
  117. for (let name of listValues())
  118. opts[name] = getValue(name, opts[name]);
  119. const checkName = name => {
  120. if (!_hasOwnProperty(opts, name))
  121. throw new Error('Attempt to access missing option value.');
  122. return true;
  123. };
  124. return new Proxy(opts, {
  125. get(opts, name) {
  126. if (name === 'toString')
  127. return () => JSON.stringify(opts);
  128. if (checkName(name))
  129. return opts[name];
  130. },
  131. set(opts, name, value) {
  132. if (checkName(name)) {
  133. opts[name] = value;
  134. setValue(name, value);
  135. }
  136. return true;
  137. }
  138. });
  139. })();
  140.  
  141. if (jsf.BlockNotificationPermissionRequests && win.Notification && win.Notification.permission === 'default') {
  142. win.Notification.requestPermission = () => new Promise(resolve => resolve('denied'));
  143. Object.defineProperty(win.Notification, 'permission', {
  144. set() {},
  145. get() {
  146. return 'denied';
  147. }
  148. });
  149. }
  150.  
  151. if (isFirefox && // Exit on image pages in Fx
  152. _document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  153. return;
  154.  
  155. // NodeList and HTMLCollection iterator polyfill
  156. // required for old versions of Safari and Chrome 49 (last available for WinXP)
  157. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  158. if (!NodeList.prototype[Symbol.iterator])
  159. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  160. if (!HTMLCollection.prototype[Symbol.iterator])
  161. HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  162.  
  163. // Stub for missing "GM.cookie.list" in unsupported script managers
  164. if (GM.cookie === undefined)
  165. GM.cookie = {
  166. list: () => ({
  167. then: () => null
  168. })
  169. };
  170.  
  171. // Wrapper to run scripts designed to override objects available to other scripts
  172. // Required in old versions of Firefox (<58) or when running with Greasemonkey
  173. const
  174. batchLand = [],
  175. batchPrepend = new Set(),
  176. _APIString = `const win = window, isFirefox = ${isFirefox}, inIFrame = ${inIFrame}, _document = win.document, _de = _document.documentElement,
  177. _Document = Object.getPrototypeOf(HTMLDocument.prototype), _Element = Object.getPrototypeOf(HTMLElement.prototype), _Node = Object.getPrototypeOf(_Element),
  178. _appendChild = _Document.appendChild.bind(_de), _removeChild = _Document.removeChild.bind(_de), skipLander = ${skipLander},
  179. _createElement = _Document.createElement.bind(_document), _querySelector = _Document.querySelector.bind(_document),
  180. _querySelectorAll = _Document.querySelectorAll.bind(_document), _bindCall = fun => Function.prototype.call.bind(fun),
  181. _getAttribute = _bindCall(_Element.getAttribute), _setAttribute = _bindCall(_Element.setAttribute),
  182. _removeAttribute = _bindCall(_Element.removeAttribute), _hasOwnProperty = _bindCall(Object.prototype.hasOwnProperty),
  183. _toString = _bindCall(Function.prototype.toString), _apply = Reflect.apply, _construct = Reflect.construct;
  184. const GM = { info: { version: '0.0', scriptHandler: null }, cookie: { list: () => ({ then: () => null }) } };
  185. const jsf = ${jsf.toString()}, _console = {}; (${_console.initConsole.toString()})();`,
  186. landScript = (f, pre) => {
  187. const script = _createElement('script');
  188. script.textContent = `(()=>{${_APIString}${[...pre].join(';')};(${f.join(')();(')})();})();`;
  189. _appendChild(script);
  190. _removeChild(script);
  191. };
  192. let scriptLander = f => f();
  193. if (!skipLander) {
  194. scriptLander = (func, ...prepend) => {
  195. prepend.forEach(x => batchPrepend.add(x));
  196. batchLand.push(func);
  197. };
  198. _document.addEventListener(
  199. 'DOMContentLoaded', () => void(scriptLander = (f, ...prep) => landScript([f], prep)), false
  200. );
  201. }
  202.  
  203. function nullTools(opts) {
  204. /* jshint validthis: true */
  205. const nt = this;
  206. opts = opts || {};
  207.  
  208. function Stats() {
  209. const updated = new Map();
  210. const logged = new Map();
  211.  
  212. function printUpdated() {
  213. const prepared = [...updated].map(x => {
  214. const [prop, dir] = x;
  215. logged.set(prop, logged.get(prop) | dir);
  216. return `${prop} (${dir ^ (Stats.GET | Stats.SET) ? (dir & Stats.GET ? 'R' : 'W') : 'R/W'})`;
  217. }).sort();
  218. updated.clear();
  219. _console.log(`Accessed properties:\n * ${prepared.join('\n * ')}`);
  220. }
  221.  
  222. let logLock;
  223. this.log = async (prop, dir, doLog) => {
  224. if (!doLog) return;
  225. if (!(logged.get(prop) & dir))
  226. updated.set(prop, updated.get(prop) | dir);
  227. logLock = (logLock > 0 || !updated.size) ? logLock : setInterval(() => {
  228. printUpdated();
  229. logLock = clearInterval(logLock);
  230. }, 2500);
  231. };
  232. }
  233. Stats.GET = 1;
  234. Stats.SET = 2;
  235. Object.freeze(Stats);
  236. const stats = new Stats();
  237.  
  238. const log = async (...args) => opts.log && _console.log(...args);
  239. const isObjecty = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  240. const parsePath = path => {
  241. let root = win,
  242. chain = path.split('.'),
  243. link = chain.shift();
  244. for (; chain.length > 0; link = chain.shift()) {
  245. if (!isObjecty(root[link]))
  246. break;
  247. root = root[link];
  248. }
  249. return [root, link, chain];
  250. };
  251.  
  252. const namedObjects = new WeakMap();
  253.  
  254. nt.destroy = function (o, destroy) {
  255. if (!opts.destroy && !destroy && o instanceof Object)
  256. return;
  257. log('cleaning', o);
  258. try {
  259. for (let item in o) {
  260. if (item instanceof Object)
  261. nt.destroy(item);
  262. delete o[item];
  263. }
  264. } catch (e) {
  265. log('Error in object destructor', e);
  266. }
  267. };
  268.  
  269. nt.define = function (path, val, other = {}) {
  270. other.enumerable = other.enumerable || false;
  271. const [obj, prop, remainder] = parsePath(path);
  272. if (remainder.length) {
  273. _console.warn(`Unable to resolve ${remainder.join('.')} in ${path}`);
  274. return;
  275. }
  276. namedObjects.set(obj, path);
  277. nt.defineOn(obj, prop, val, path, other);
  278. };
  279.  
  280. nt.defineOn = function (obj, prop, val, path, other = {}) {
  281. path = path || ((obj === win) ? prop : `?.${prop}`);
  282. if (path[path.length - 1] === '.')
  283. path = `${path}${prop}`;
  284. const desc = Object.getOwnPropertyDescriptor(obj, prop);
  285. if (desc !== undefined && !desc.configurable) {
  286. _console.warn(`Unable to redefine not configurable ${prop} in`, obj);
  287. return;
  288. }
  289. const doLog = other.trace || jsf.AccessStatistics || opts.trace;
  290. Object.defineProperty(
  291. obj, prop, {
  292. get() {
  293. stats.log(path, Stats.GET, doLog);
  294. return val;
  295. },
  296. set(v) {
  297. stats.log(path, Stats.SET, doLog);
  298. if (v !== val) {
  299. log(`set ${prop} of`, obj, 'to', v);
  300. nt.destroy(v);
  301. }
  302. },
  303. enumerable: other.enumerable
  304. }
  305. );
  306. };
  307.  
  308. nt.proxy = function (obj, name, opts = {}) {
  309. if (name) namedObjects.set(obj, name);
  310. return new Proxy(
  311. obj, {
  312. get(that, prop) {
  313. if (prop in that)
  314. return that[prop];
  315. if (typeof prop === 'symbol') {
  316. if (prop === Symbol.toPrimitive)
  317. that[prop] = function (hint) {
  318. if (hint === 'string')
  319. return Object.prototype.toString.call(this);
  320. return `[missing toPrimitive] ${name} ${hint}`;
  321. };
  322. else if (prop === Symbol.toStringTag)
  323. that[prop] = () => 'Object';
  324. else {
  325. that[prop] = undefined;
  326. _console.trace('Missing', prop, 'in', name || '?', '>>', that[prop]);
  327. }
  328. return that[prop];
  329. }
  330. if (name) {
  331. that[prop] = nt.func(opts.val, `${name}.${prop}`, opts.log);
  332. return that[prop];
  333. }
  334. _console.trace('Missing', prop, 'in', namedObjects.get(that) || that);
  335. },
  336. set(that, prop, val) {
  337. if (val !== that[prop]) {
  338. log('skip set', prop, 'of', namedObjects.get(that) || that, 'to', val);
  339. nt.destroy(val);
  340. }
  341. return true;
  342. }
  343. }
  344. );
  345. };
  346.  
  347. nt.func = (val, name, log = opts.log || opts.trace) => nt.proxy((() => {
  348. let f = function () {
  349. if (log) _console.trace(`call ${name || ''}(`, ...arguments, `) return`, val);
  350. return val;
  351. };
  352. if (name) namedObjects.set(f, name);
  353. return f;
  354. })());
  355.  
  356. nt.NULL = {
  357. val: null
  358. };
  359. Object.freeze(nt.NULL);
  360.  
  361. Object.freeze(nt);
  362. }
  363. nullTools.toString = new Proxy(nullTools.toString, {
  364. apply(...args) {
  365. return `${_apply(...args)} let nt = new nullTools();`;
  366. }
  367. });
  368. let nt = new nullTools();
  369.  
  370. // Creates and return protected style (unless protection is manually disabled).
  371. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  372.  
  373. const createStyle = (function createStyleModule() {
  374. function createStyleElement(rules, opts) {
  375. const style = _createElement('style');
  376. Object.assign(style, opts.props);
  377. opts.root.appendChild(style);
  378.  
  379. if (style.sheet) // style.sheet is only available when style attached to DOM
  380. rules.forEach(style.sheet.insertRule.bind(style.sheet));
  381. else
  382. style.textContent = rules.join('\n');
  383.  
  384. if (opts.protect) {
  385. Object.defineProperty(style, 'sheet', {
  386. value: null,
  387. enumerable: true
  388. });
  389. Object.defineProperty(style, 'disabled', { //pretend to be disabled
  390. enumerable: true,
  391. set() {},
  392. get() {
  393. return true;
  394. }
  395. });
  396. (new MutationObserver(
  397. () => opts.root.removeChild(style)
  398. )).observe(style, {
  399. childList: true
  400. });
  401. }
  402.  
  403. return style;
  404. }
  405.  
  406. // functions to parse object-based rulesets
  407. function parseRule(rec) {
  408. /* jshint validthis: true */
  409. return this.concat(rec[0], ' {\n', Object.entries(rec[1]).map(parseProperty, this + '\t').join('\n'), '\n', this, '}');
  410. }
  411.  
  412. function parseProperty(rec) {
  413. /* jshint validthis: true */
  414. return rec[1] instanceof Object ? parseRule.call(this, rec) : `${this}${rec[0].replace(/_/g, '-')}: ${rec[1]};`;
  415. }
  416.  
  417. // main
  418. const createStyle = (rules, opts) => {
  419. // parse options
  420. opts = Object.assign({
  421. protect: true,
  422. root: _de,
  423. type: 'text/css'
  424. }, opts);
  425. // move style properties into separate property
  426. // { a, b, ...rest } construction is not available in Fx 52
  427. opts.props = Object.assign({}, opts);
  428. delete opts.props.protect;
  429. delete opts.props.root;
  430. // store binded methods instead of element
  431. opts.root = {
  432. appendChild: opts.root.appendChild.bind(opts.root),
  433. removeChild: opts.root.removeChild.bind(opts.root)
  434. };
  435.  
  436. // convert rules set into an array if it isn't one already
  437. rules = Array.isArray(rules) ? rules : rules instanceof Object ? Object.entries(rules).map(parseRule, '') : [rules];
  438.  
  439. // could be reassigned when protection triggered
  440. let style = createStyleElement(rules, opts);
  441.  
  442. if (!opts.protect)
  443. return style;
  444.  
  445. const replaceStyle = () => new Promise(
  446. resolve => setTimeout(re => re(createStyleElement(rules, opts)), 0, resolve)
  447. ).then(st => (style = st)); // replace poiner to style object with a new style object
  448.  
  449. (new MutationObserver(ms => {
  450. for (let m of ms)
  451. for (let node of m.removedNodes)
  452. if (node === style) replaceStyle();
  453. })).observe(_de, {
  454. childList: true
  455. });
  456.  
  457. return style;
  458. };
  459. createStyle.toString = () => `const createStyle = (${createStyleModule.toString()})();`;
  460. return createStyle;
  461. })();
  462.  
  463. // aborts currently running script with ReferenceError on specific property access
  464. // in case of inline script also checks if it contains specific pattern in it
  465.  
  466. const abortExecution = (function abortExecutionModule() {
  467. let map = new Map(),
  468. cnt = new Map(),
  469. stack = 0;
  470. const printCounters = (cnts) => {
  471. let s = '';
  472. for (let cntr of cnts)
  473. s += `\n * ${cntr[0]}: ${cntr[1]}`;
  474. return s;
  475. };
  476. const logger = id => {
  477. if (!jsf.AbortExecutionStatistics)
  478. return;
  479. let {
  480. path,
  481. mode
  482. } = map.get(id);
  483. let prop = `${path} ${mode.toString().replace('Symbol','')}`;
  484. cnt.set(prop, (cnt.get(prop) || 0) + 1);
  485. stack++;
  486. setTimeout(() => {
  487. stack--;
  488. if (!stack)
  489. console.log('Abort execution counters:', printCounters(Array.from(cnt.entries())));
  490. }, 1000);
  491. };
  492. const isObjecty = x => (x !== null) && typeof x === 'object' || typeof x === 'function';
  493. const Mode = {
  494. Get: Symbol('Read'),
  495. Set: Symbol('Write'),
  496. All: Symbol('Access'),
  497. InlineScript: Symbol('InlineScript')
  498. };
  499. Object.freeze(Mode);
  500.  
  501. const abortExecution = function abortExecution(mode, path, conf = {}) {
  502. let root = conf.root || win,
  503. chain = path.split('.'),
  504. postponed = false;
  505. const postpone = (link, chain) => {
  506. postponed = true;
  507. let _val;
  508. try {
  509. Object.defineProperty(root, link, {
  510. get() {
  511. return _val;
  512. },
  513. set(val) {
  514. _val = val;
  515. conf.root = val;
  516. conf.fullPath = conf.fullPath || path;
  517. abortExecution(mode, chain.join('.'), conf);
  518. }
  519. });
  520. } catch (e) {
  521. _console.warn(`Unable to set postpone point at ${link} in ${path}\n`, e);
  522. }
  523. };
  524. while (chain.length > 1) {
  525. let link = chain.shift();
  526. if (!isObjecty(root[link])) {
  527. if (conf.breakOnMissing)
  528. break;
  529. postpone(link, chain);
  530. break;
  531. }
  532. root = root[link];
  533. }
  534. path = conf.fullPath || path;
  535. if (postponed) {
  536. if (conf.breakOnMissing)
  537. _console.log(`Unable to locate "${path}", abort anchor skipped.`);
  538. return;
  539. }
  540. const target = chain[0];
  541. const message = `${target} is not defined`;
  542. const des = Object.getOwnPropertyDescriptor(root, target);
  543. if (des && des.get !== undefined)
  544. return;
  545. const id = Math.random().toString(36).substr(2);
  546. map.set(id, {
  547. path: path,
  548. mode: mode
  549. });
  550. win.addEventListener('error', e => {
  551. if (e.error && e.error.message === message)
  552. e.stopImmediatePropagation();
  553. }, false);
  554. const get = Symbol('get');
  555. const set = Symbol('set');
  556.  
  557. const removeOwnFootprint = e => (e.stack = e.stack.split('\n').filter(x => !x.includes('-extension://')).join('\n'), e);
  558. const check = (mode === Mode.InlineScript) ?
  559. () => {
  560. const script = _document.currentScript;
  561. if (script && script.src === '' &&
  562. (!conf.pattern || conf.pattern.test(script.textContent))) {
  563. logger(id);
  564. throw removeOwnFootprint(new ReferenceError(message));
  565. }
  566. } : io => {
  567. if (io === set && mode === Mode.Get ||
  568. io === get && mode === Mode.Set)
  569. return;
  570. logger(id);
  571. throw removeOwnFootprint(new ReferenceError(message));
  572. };
  573.  
  574. let _val = root[target];
  575. Object.defineProperty(root, target, {
  576. get() {
  577. check(get);
  578. return _val;
  579. },
  580. set(v) {
  581. check(set);
  582. _val = v;
  583. }
  584. });
  585. };
  586. abortExecution.onGet = (path, conf) => abortExecution(Mode.Get, path, conf);
  587. abortExecution.onSet = (path, conf) => abortExecution(Mode.Set, path, conf);
  588. abortExecution.onAll = (path, conf) => abortExecution(Mode.All, path, conf);
  589. abortExecution.inlineScript = (path, conf) => abortExecution(Mode.InlineScript, path, conf);
  590. abortExecution.toString = () => ` const abortExecution = (${abortExecutionModule.toString()})();`;
  591. return abortExecution;
  592. })();
  593.  
  594. // Fake objects of advertisement networks to break their workflow
  595. // Popular adblock detector
  596. function deployFABStub(root) {
  597. if (!('fuckAdBlock' in root)) {
  598. let FuckAdBlock = function (options) {
  599. let self = this;
  600. self._options = {
  601. checkOnLoad: false,
  602. resetOnEnd: false,
  603. checking: false
  604. };
  605. self.setOption = function (opt, val) {
  606. if (val)
  607. self._options[opt] = val;
  608. else
  609. Object.assign(self._options, opt);
  610. };
  611. if (options)
  612. self.setOption(options);
  613.  
  614. self._var = {
  615. event: {}
  616. };
  617. self.clearEvent = function () {
  618. self._var.event.detected = [];
  619. self._var.event.notDetected = [];
  620. };
  621. self.clearEvent();
  622.  
  623. self.on = function (detected, fun) {
  624. self._var.event[detected ? 'detected' : 'notDetected'].push(fun);
  625. return self;
  626. };
  627. self.onDetected = function (cb) {
  628. return self.on(true, cb);
  629. };
  630. self.onNotDetected = function (cb) {
  631. return self.on(false, cb);
  632. };
  633. self.emitEvent = function () {
  634. for (let fun of self._var.event.notDetected)
  635. fun();
  636. if (self._options.resetOnEnd)
  637. self.clearEvent();
  638. return self;
  639. };
  640. self._creatBait = () => null;
  641. self._destroyBait = () => null;
  642. self._checkBait = function () {
  643. setTimeout((() => self.emitEvent()), 1);
  644. };
  645. self.check = function () {
  646. self._checkBait();
  647. return true;
  648. };
  649.  
  650. let callback = function () {
  651. if (self._options.checkOnLoad)
  652. setTimeout(self.check, 1);
  653. };
  654. root.addEventListener('load', callback, false);
  655. };
  656. nt.defineOn(root, 'FuckAdBlock', FuckAdBlock);
  657. nt.defineOn(root, 'fuckAdBlock', new FuckAdBlock({
  658. checkOnLoad: true,
  659. resetOnEnd: true
  660. }));
  661. }
  662. }
  663. // new version of fAB adapting to fake API
  664. // scriptLander(() => deployFABStub(win), nullTools); // so it's disabled by default for now
  665.  
  666. scriptLander(() => {
  667. // VideoJS player wrapper
  668. {
  669. let _videojs = win.videojs;
  670. Object.defineProperty(win, 'videojs', {
  671. get() {
  672. return _videojs;
  673. },
  674. set(f) {
  675. if (f === _videojs)
  676. return true;
  677. _console.log('videojs =', f);
  678. _videojs = new Proxy(f, {
  679. apply(fun, that, args) {
  680. _console.log('videojs(', ...args, ')');
  681. const params = args[1];
  682. if (params) {
  683. if (params.hasAd)
  684. params.hasAd = false;
  685. if (params.plugins && params.plugins.vastClient)
  686. delete params.plugins.vastClient;
  687. // disable unmuted autoplay (muted used for preview purposes)
  688. if (params.autoplay && !params.muted)
  689. params.autoplay = false;
  690. }
  691. const res = _apply(fun, that, args);
  692. if (res.seed)
  693. res.seed = () => null;
  694. if (res.on && res.off) {
  695. const logPlayer = () => {
  696. _console.log('player =', res);
  697. res.off('playing', logPlayer);
  698. };
  699. res.on('playing', logPlayer);
  700. }
  701. return res;
  702. }
  703. });
  704. }
  705. });
  706. }
  707.  
  708. // Set a little trap for BodyClick ads
  709. abortExecution.onSet('__BC_domain');
  710.  
  711. // Yandex API (ADBTools, Metrika)
  712. let hostname = location.hostname;
  713. if ( // Thank you, Greasemonkey, now I have to check for this. -_-
  714. location.protocol === 'about:' ||
  715. // Google likes to define odd global variables like Ya
  716. hostname.startsWith('google.') || hostname.includes('.google.') ||
  717. // Also, Yandex uses their Ya object for a lot of things on their pages and
  718. // wrapping it may cause problems. It's better to skip it in some cases.
  719. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  720. /^\/((yand)?search|images|health)/i.test(location.pathname) && !hostname.startsWith('news.')) ||
  721. // Also skip on these following sites since they use
  722. // code minification which generated global Ya variable.
  723. hostname.endsWith('chatango.com') || hostname.endsWith('github.io') ||
  724. hostname.endsWith('grimtools.com') || hostname.endsWith('poeplanner.com'))
  725. return;
  726.  
  727. let YaProps = new Set();
  728.  
  729. function setObfuscatedProperty(Ya, rootProp, obj, name) {
  730. if (YaProps.has(rootProp))
  731. return;
  732. _console.trace(`Ya.${rootProp} = Ya.${name}`);
  733. nt.defineOn(Ya, rootProp, Ya[name], 'Ya.');
  734. YaProps.add(rootProp);
  735. for (let prop in obj)
  736. delete obj[prop];
  737. for (let prop in Ya[name])
  738. obj[prop] = Ya[name][prop];
  739. }
  740.  
  741. function onObfuscatedProperty(Ya, rootProp, obj) {
  742. if ('AdvManager' in obj || 'AdvManagerStatic' in obj || 'isAllowedRepeatAds' in obj) {
  743. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  744. return Ya.Context;
  745. }
  746. if ('create' in obj && 'createAdaptive' in obj && 'createScroll' in obj) {
  747. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  748. return Ya.adfoxCode;
  749. }
  750. return new Proxy(obj, {
  751. set(target, prop, val) {
  752. if (prop === 'AdvManager' || prop === 'isAllowedRepeatAds') {
  753. setObfuscatedProperty(Ya, rootProp, obj, 'Context');
  754. return true;
  755. }
  756. if (prop === 'create' && 'createAdaptive' in obj && 'createScroll' in obj ||
  757. prop === 'createScroll' && 'create' in obj && 'createAdaptive' in obj ||
  758. prop === 'createAdaptive' && 'create' in obj && 'createScroll' in obj) {
  759. setObfuscatedProperty(Ya, rootProp, obj, 'adfoxCode');
  760. return true;
  761. }
  762. target[prop] = val;
  763. return true;
  764. },
  765. get(target, prop) {
  766. if (prop === 'AdvManager' && !(prop in target)) {
  767. _console.trace(`Injected missing ${prop} in Ya.${rootProp}.`);
  768. target[prop] = Ya.Context[prop];
  769. }
  770. return target[prop];
  771. }
  772. });
  773. }
  774. let Rum = {
  775. getSettings: nt.func([], 'Ya.Rum.getSettings'),
  776. getVarsList: nt.func([], 'Ya.Rum.getVarsList'),
  777. ajaxStart: 0,
  778. ajaxComplete: 0,
  779. enabled: true,
  780. vsChanged: false,
  781. vsStart: 'visible',
  782. ERROR_LEVEL: nt.proxy({
  783. ERROR: 0,
  784. WARN: 0,
  785. INFO: 0
  786. }, 'Ya.Rum.ERROR_LEVEL'),
  787. _tti: null,
  788. _markListeners: nt.proxy({}, 'Ya.Rum._markListeners'),
  789. _periodicTasks: nt.proxy({}, 'Ya.Rum._periodicTasks')
  790. };
  791. [
  792. '__timeMarks', '_timeMarks', '__deltaMarks', '_deltaMarks',
  793. '__defRes', '_defRes', '__defTimes', '_defTimes', '_vars',
  794. 'commonVars'
  795. ].forEach(name => void(Rum[name] = []));
  796. Rum = nt.proxy(Rum, 'Ya.Rum', nt.NULL);
  797. let Ya = new Proxy({}, {
  798. set(obj, prop, val) {
  799. if (val === obj[prop])
  800. return true;
  801. if (prop === 'Rum') {
  802. nt.defineOn(obj, prop, Rum, 'Ya.');
  803. YaProps.add(prop);
  804. Object.assign(val, Rum);
  805. }
  806. if (YaProps.has(prop)) {
  807. _console.log(`Ya.${prop} \u2260`, val);
  808. return true;
  809. }
  810. if (typeof val === 'object' && prop !== '__inline_params__' && !('length' in val))
  811. val = onObfuscatedProperty(Ya, prop, val);
  812. obj[prop] = val;
  813. _console.log(`Ya.${prop} =`, val);
  814. return true;
  815. },
  816. get(obj, prop) {
  817. return obj[prop];
  818. }
  819. });
  820. let callWithParams = function (f) {
  821. f.call(this, Ya.__inline_params__ || {});
  822. Ya.__inline_params__ = null;
  823. };
  824. nt.defineOn(Ya, 'callWithParams', callWithParams, 'Ya.');
  825. nt.defineOn(Ya, 'PerfCounters', nt.proxy({
  826. __cacheEvents: []
  827. }, 'Ya.PerfCounters', nt.NULL), 'Ya.');
  828. nt.defineOn(Ya, '__isSent', true, 'Ya.');
  829. nt.defineOn(Ya, 'confirmUrl', '', 'Ya.');
  830. nt.defineOn(Ya, 'Direct', nt.proxy({}, 'Ya.Direct', nt.NULL), 'Ya.');
  831. nt.defineOn(Ya, 'mediaCode', nt.proxy({
  832. create() {
  833. if (inIFrame) {
  834. _console.log('Removed body of ad-frame.');
  835. _document.documentElement.removeChild(_document.body);
  836. }
  837. }
  838. }, 'Ya.mediaCode', nt.NULL), 'Ya.');
  839. let extra = nt.proxy({
  840. extra: nt.proxy({
  841. match: 0,
  842. confirm: '',
  843. src: ''
  844. }),
  845. id: 0,
  846. percent: 100,
  847. threshold: 1
  848. });
  849. nt.defineOn(Ya, '_exp', nt.proxy({
  850. id: 0,
  851. coin: 0,
  852. choose: nt.func(extra, 'Ya._exp.choose'),
  853. get(prop) {
  854. return _hasOwnProperty(extra, prop) ? extra[prop] : null;
  855. },
  856. getId: nt.func(0, 'Ya._exp.getId'),
  857. defaultVersion: extra,
  858. getExtra: nt.func(extra.extra, 'Ya._exp.getExtra'),
  859. getDefaultExtra: nt.func(extra.extra, 'Ya._exp.getDefaultExtra'),
  860. versions: [extra]
  861. }), 'Ya.');
  862. nt.defineOn(Ya, 'c', nt.func(null, 'Ya.c'), 'Ya.');
  863. nt.defineOn(Ya, 'ADBTools', function () {
  864. this.getCurrentState = nt.func(true, 'Ya.ADBTools().getCurrentState');
  865. return nt.proxy(this, 'Ya.ADBTools', nt.NULL);
  866. }, 'Ya.');
  867. nt.defineOn(Ya, 'AdDetector', nt.proxy({}, 'Ya.AdDetector', nt.NULL), 'Ya.');
  868. let definePr = o => {
  869. Object.defineProperty(o, 'pr', {
  870. set() {},
  871. get() {
  872. return Math.floor(Math.random() * 1e6) + 1;
  873. }
  874. });
  875. };
  876. let adfoxCode = {
  877. forcedDirectLoadingExp: nt.proxy({
  878. isLoadingTurnedOn: false,
  879. isExp: false
  880. }),
  881. isLoadingTurnedOn: false,
  882. xhrExperiment: nt.proxy({
  883. isXhr: true,
  884. isControl: true
  885. }),
  886. matchidManager: nt.proxy({}, 'Ya.adfoxCode.matchidManager', nt.NULL),
  887. _: []
  888. };
  889. definePr(adfoxCode);
  890. [
  891. 'clearSession', 'create', 'createAdaptive', 'createScroll',
  892. 'destroy', 'moduleLoad', 'reload', 'setModule'
  893. ].forEach(name => void(adfoxCode[name] = nt.func(null, `Ya.adfoxCode.${name}`)));
  894. nt.defineOn(Ya, 'adfoxCode', nt.proxy(adfoxCode, 'Ya.adfoxCode', nt.NULL), 'Ya.');
  895. let managerForAdfox = {
  896. loaderVersion: 1,
  897. isCurrrencyExp: true,
  898. isReady: nt.func(true, 'Ya.headerBidding.managerForAdfox.isReady'),
  899. getRequestTimeout: nt.func(
  900. 300 + Math.floor(Math.random() * 100),
  901. 'Ya.headerBidding.managerForAdfox.getRequestTimeout'
  902. )
  903. };
  904. let headerBidding = nt.proxy({
  905. setSettings(opts) {
  906. if (!(opts && opts.adUnits))
  907. return null;
  908. let ids = [];
  909. for (let unit of opts.adUnits)
  910. ids.push(unit.code);
  911. createStyle(`#${ids.join(', #')} { display: none !important }`);
  912. },
  913. pushAdUnits: nt.func(null, 'Ya.headerBidding.pushAdUnits'),
  914. managerForAdfox: nt.proxy(managerForAdfox, 'Ya.headerBidding.managerForAdfox', nt.NULL)
  915. });
  916. definePr(headerBidding);
  917. nt.defineOn(Ya, 'headerBidding', headerBidding, 'Ya.');
  918.  
  919. let AdvManager = function () {
  920. this.render = function (o) {
  921. if (!o.renderTo)
  922. return;
  923. let placeholder = _document.getElementById(o.renderTo);
  924. if (!placeholder)
  925. return _console.warn('Ya.AdvManager.render call w/o placeholder', o);
  926. let parent = placeholder.parentNode;
  927. placeholder.style = 'display:none!important';
  928. parent.style = (parent.getAttribute('style') || '') + 'height:auto!important';
  929. // fix for Yandex TV pages
  930. if (location.hostname.startsWith('tv.yandex.')) {
  931. let sibling = placeholder.previousSibling;
  932. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  933. sibling.style.display = 'none';
  934. }
  935. };
  936. this.constructor = Object;
  937. return nt.proxy(this, 'Ya.AdvManager', nt.NULL);
  938. };
  939. nt.defineOn(Ya, 'Context', new Proxy({
  940. __longExperiment: null,
  941. _callbacks: nt.proxy([]),
  942. _asyncModeOn: true,
  943. _init: nt.func(null, 'Ya.Context._init'),
  944. _load_callbacks: nt.proxy([]),
  945. performanceStorage: nt.proxy({}),
  946. processCallbacks: nt.func(null, 'Ya.Context.processCallbacks'),
  947. isAllowedRepeatAds: nt.func(null, 'Ya.Context.isAllowedRepeatAds'),
  948. isNewLoader: nt.func(false, 'Ya.Context.isNewLoader'),
  949. getItem: nt.func(null, 'Ya.Context.getItem'),
  950. AdvManager: new AdvManager(),
  951. AdvManagerStatic: new AdvManager()
  952. }, {
  953. get(obj, prop) {
  954. if (prop in obj)
  955. return obj[prop];
  956. _console.trace(`Ya.Context.${prop} = Ya.Context.AdvManager`);
  957. obj[prop] = obj.AdvManager;
  958. return obj[prop];
  959. },
  960. set() {
  961. return true;
  962. }
  963. }), 'Ya.');
  964. let Metrika = function Metrika(x) {
  965. this._ecommerce = '';
  966. if (x && 'id' in x)
  967. this.id = x.id;
  968. else
  969. this.id = 0;
  970. return nt.proxy(this, 'Ya.Metrika', nt.NULL);
  971. };
  972. Metrika.counters = () => Ya._metrika.counters;
  973. nt.defineOn(Ya, 'Metrika', Metrika, 'Ya.');
  974. nt.defineOn(Ya, 'Metrika2', Metrika, 'Ya.');
  975. let counter = new Metrika();
  976. nt.defineOn(Ya, '_metrika', nt.proxy({
  977. counter: counter,
  978. counters: [counter],
  979. hitParam: {},
  980. counterNum: 0,
  981. hitId: 0,
  982. v: 1,
  983. i: 0,
  984. _globalMetrikaHitId: 0,
  985. getCounters: null,
  986. dataLayer: null,
  987. f1: null
  988. }), 'Ya.');
  989. nt.defineOn(Ya, '_globalMetrikaHitId', 0, 'Ya.');
  990. counter = {};
  991. [
  992. 'stringifyParams', '_getVars',
  993. 'getUid', 'getUrl', 'getHash'
  994. ].forEach(name => void(counter[name] = nt.func('', `Ya.counter.${name}`)));
  995. nt.defineOn(Ya, 'counter', nt.proxy(counter, 'Ya.counter', nt.NULL), 'Ya.');
  996. nt.defineOn(Ya, 'jserrors', [], 'Ya.');
  997. nt.defineOn(Ya, 'onerror', nt.func(null, 'Ya.onerror'), 'Ya.');
  998. let error_on_access = false;
  999. if ('Ya' in win)
  1000. try {
  1001. _console.log('Found existing Ya object:', win.Ya);
  1002. for (let prop in win.Ya)
  1003. Ya[prop] = win.Ya[prop];
  1004. } catch (ignore) {
  1005. error_on_access = true;
  1006. }
  1007. if (!error_on_access && // some people don't know how to export only necessary stuff into global context
  1008. location.hostname !== 'material.io') { // so, here is an exception for one of such cases
  1009. for (let prop in Ya)
  1010. if (prop !== '__inline_params__')
  1011. YaProps.add(prop);
  1012. nt.define('Ya', Ya);
  1013. } else
  1014. _console.warn('Looks like window.Ya blocked with error-on-access scriptlet.');
  1015. // Yandex.Metrika callbacks
  1016. let yandex_metrika_callbacks = [];
  1017. _document.addEventListener(
  1018. 'DOMContentLoaded', () => {
  1019. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  1020. yandex_metrika_callbacks.length = 0;
  1021. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  1022. }, false
  1023. );
  1024. nt.define('yandex_metrika_callbacks', yandex_metrika_callbacks);
  1025. }, nullTools, createStyle, abortExecution);
  1026.  
  1027. // Yandex Raven stub (some monitoring sub-system)
  1028. function yandexRavenStub() {
  1029. let nt = new nullTools({
  1030. log: true
  1031. });
  1032. nt.define('Raven', nt.proxy({
  1033. context(f) {
  1034. return f();
  1035. },
  1036. config: nt.func(
  1037. nt.proxy({}, 'Raven.config', {
  1038. val: nt.proxy({}, 'Raven.config()..', nt.NULL)
  1039. }), 'Raven.config')
  1040. }, 'Raven', nt.NULL));
  1041. }
  1042.  
  1043. // Based on https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8
  1044. {
  1045. const log = name => _console.log(`Player FIX: Detected ${name} player in ${location.href}`);
  1046. const removeVast = (data) => {
  1047. if (data && typeof data === 'object') {
  1048. _console.log('Player configuration:', data);
  1049. if (data.advert_script && data.advert_script !== '') {
  1050. _console.log('Set data.advert_script to empty string.');
  1051. data.advert_script = '';
  1052. }
  1053. let keys = Object.getOwnPropertyNames(data);
  1054. let isVast = name => /vast|clickunder/.test(name);
  1055. if (!keys.some(isVast))
  1056. return data;
  1057. for (let key of keys)
  1058. if (typeof data[key] === 'object' && key !== 'links') {
  1059. _console.log(`Removed data.${key}:`, data[key]);
  1060. delete data[key];
  1061. }
  1062. if (data.chain) {
  1063. let need = [],
  1064. drop = [],
  1065. links = data.chain.split('.');
  1066. for (let link of links)
  1067. if (!isVast(link))
  1068. need.push(link);
  1069. else
  1070. drop.push(link);
  1071. _console.log('Dropped from the chain:', ...drop);
  1072. data.chain = need.join('.');
  1073. }
  1074. }
  1075. return data;
  1076. };
  1077.  
  1078. _document.addEventListener(
  1079. 'DOMContentLoaded',
  1080. function () {
  1081. if ('video_balancer_options' in win && 'event_callback' in win) {
  1082. log('Moonwalk');
  1083. if (win.video_balancer_options.adv)
  1084. removeVast(win.video_balancer_options.adv);
  1085. if ('_mw_adb' in win)
  1086. Object.defineProperty(win, '_mw_adb', {
  1087. set() {},
  1088. get() {
  1089. return false;
  1090. }
  1091. });
  1092. } else if (win.startKodikPlayer !== undefined) {
  1093. log('Kodik');
  1094. // skip attempt to block access to HD resolutions
  1095. const chainCall = new Proxy({}, {
  1096. get() {
  1097. return () => chainCall;
  1098. }
  1099. });
  1100. if (win.$ && win.$.prototype && win.$.prototype.addClass) {
  1101. let $addClass = win.$.prototype.addClass;
  1102. win.$.prototype.addClass = function (className) {
  1103. if (className === 'blocked')
  1104. return chainCall;
  1105. return $addClass.apply(this, arguments);
  1106. };
  1107. }
  1108. // remove ad links from the metadata
  1109. let _ajax = win.$.ajax;
  1110. win.$.ajax = (params, ...args) => {
  1111. if (params.success) {
  1112. let _s = params.success;
  1113. params.success = (data, ...args) => _s(removeVast(data), ...args);
  1114. }
  1115. return _ajax(params, ...args);
  1116. };
  1117. } else if (win.getnextepisode && win.uppodEvent) {
  1118. log('Share-Serials.net');
  1119. scriptLander(
  1120. function () {
  1121. let _setInterval = win.setInterval,
  1122. _setTimeout = win.setTimeout;
  1123. win.setInterval = function (func) {
  1124. if (typeof func === 'function' && _toString(func).includes('_delay')) {
  1125. let intv = _setInterval.call(
  1126. this,
  1127. function () {
  1128. _setTimeout.call(
  1129. this,
  1130. function (intv) {
  1131. clearInterval(intv);
  1132. let timer = _document.querySelector('#timer');
  1133. if (timer)
  1134. timer.click();
  1135. }, 100, intv);
  1136. func.call(this);
  1137. }, 5
  1138. );
  1139.  
  1140. return intv;
  1141. }
  1142. return _setInterval.apply(this, arguments);
  1143. };
  1144. win.setTimeout = function (func) {
  1145. if (typeof func === 'function' && _toString(func).includes('adv_showed'))
  1146. return _setTimeout.call(this, func, 0);
  1147. return _setTimeout.apply(this, arguments);
  1148. };
  1149. }
  1150. );
  1151. } else if ('ADC' in win) {
  1152. log('vjs-creatives plugin in');
  1153. let replacer = (obj) => {
  1154. for (let name in obj)
  1155. if (typeof obj[name] === 'function')
  1156. obj[name] = () => null;
  1157. };
  1158. replacer(win.ADC);
  1159. replacer(win.currentAdSlot);
  1160. } else if ('Playerjs' in win) {
  1161. log('Playerjs');
  1162. win.Playerjs = new Proxy(win.Playerjs, {
  1163. construct(fn, args) {
  1164. let params = args[0];
  1165. if (params && typeof params === 'object') {
  1166. delete params.preroll;
  1167. params = removeVast(params);
  1168. Object.defineProperty(params, 'hasOwnProperty', {
  1169. value(...args) {
  1170. let res = _hasOwnProperty(this, ...args);
  1171. if (typeof args[0] === 'string' && args[0].startsWith('vast_') &&
  1172. res && params[args[0]]) {
  1173. _console.log(`Removed params.${args[0]}:`, params[args[0]]);
  1174. delete params[args[0]];
  1175. return false;
  1176. }
  1177. return res;
  1178. },
  1179. enumerable: false,
  1180. configurable: true
  1181. });
  1182. }
  1183. return _construct(fn, args);
  1184. }
  1185. });
  1186. }
  1187.  
  1188. UberVK: {
  1189. if (!inIFrame)
  1190. break UberVK;
  1191. let oddNames = 'HD' in win &&
  1192. !Object.getOwnPropertyNames(win).every(n => !n.startsWith('_0x'));
  1193. if (!oddNames)
  1194. break UberVK;
  1195. log('UberVK');
  1196. XMLHttpRequest.prototype.open = () => {
  1197. throw 404;
  1198. };
  1199. }
  1200. }, false
  1201. );
  1202. }
  1203.  
  1204. // Applies wrapper function on the current page and all newly created same-origin iframes
  1205. // This is used to prevent trick which allows to get fresh page API through newly created same-origin iframes
  1206. function deepWrapAPI(wrapper) {
  1207. let wrapped = new WeakSet();
  1208. const
  1209. log = (...args) => false && _console.log(...args),
  1210. _HTMLIFrameElement = HTMLIFrameElement.prototype,
  1211. isIFrameElement = _HTMLIFrameElement.isPrototypeOf.bind(_HTMLIFrameElement),
  1212. _contentWindow = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentWindow'),
  1213. _get_contentWindow = _bindCall(_contentWindow.get);
  1214.  
  1215. function wrapAPI(root) {
  1216. if (!root || wrapped.has(root))
  1217. return;
  1218. wrapped.add(root);
  1219. try {
  1220. wrapper(isIFrameElement(root) ? _get_contentWindow(root) : root);
  1221. log('Wrapped API in', (root === win) ? "main window." : root);
  1222. } catch (e) {
  1223. log('Failed to wrap API in', (root === win) ? "main window." : root, '\n', e);
  1224. }
  1225. }
  1226.  
  1227. // wrap API on contentWindow access
  1228. const getter = {
  1229. apply(get, that, args) {
  1230. wrapAPI(that);
  1231. return _apply(get, that, args);
  1232. }
  1233. };
  1234. _contentWindow.get = new Proxy(_contentWindow.get, getter);
  1235. Object.defineProperty(_HTMLIFrameElement, 'contentWindow', _contentWindow);
  1236. // wrap API on contentDocument access
  1237. const _contentDocument = Object.getOwnPropertyDescriptor(_HTMLIFrameElement, 'contentDocument');
  1238. _contentDocument.get = new Proxy(_contentDocument.get, getter);
  1239. Object.defineProperty(_HTMLIFrameElement, 'contentDocument', _contentDocument);
  1240.  
  1241. // manual children objects traverser to avoid issues
  1242. // with calling querySelectorAll on wrong types of objects
  1243. const
  1244. _nodeType = _bindCall(Object.getOwnPropertyDescriptor(_Node, 'nodeType').get),
  1245. _childNodes = _bindCall(Object.getOwnPropertyDescriptor(_Node, 'childNodes').get),
  1246. _ELEMENT_NODE = _Node.ELEMENT_NODE,
  1247. _DOCUMENT_FRAGMENT_NODE = _Node.DOCUMENT_FRAGMENT_NODE;
  1248. const wrapFrames = root => {
  1249. if (_nodeType(root) !== _ELEMENT_NODE && _nodeType(root) !== _DOCUMENT_FRAGMENT_NODE)
  1250. return; // only process nodes which may contain an IFRAME or be one
  1251. if (isIFrameElement(root)) {
  1252. wrapAPI(root);
  1253. return;
  1254. }
  1255. for (let child of _childNodes(root))
  1256. wrapFrames(child);
  1257. };
  1258.  
  1259. // wrap API in a newly appended iframe objects
  1260. _Node.appendChild = new Proxy(_Node.appendChild, {
  1261. apply(fun, that, args) {
  1262. let res = _apply(fun, that, args);
  1263. wrapFrames(args[0]);
  1264. return res;
  1265. }
  1266. });
  1267.  
  1268. // wrap API in iframe objects created with innerHTML of element on page
  1269. const _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  1270. _innerHTML.set = new Proxy(_innerHTML.set, {
  1271. apply(set, that, args) {
  1272. _apply(set, that, args);
  1273. if (_document.contains(that))
  1274. wrapFrames(that);
  1275. }
  1276. });
  1277. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  1278.  
  1279. wrapAPI(win);
  1280. }
  1281.  
  1282. // piguiqproxy.com / zmctrack.net circumvention and onerror callback prevention
  1283. scriptLander(
  1284. () => {
  1285. // onerror callback blacklist
  1286. let masks = [],
  1287. //blockAll = /(^|\.)(rutracker-org\.appspot\.com)$/,
  1288. isBlocked = url => masks.some(mask => mask.test(url)); // || blockAll.test(location.hostname);
  1289. for (let filter of [ // blacklist
  1290. // global
  1291. '/adv/www/',
  1292. // adservers
  1293. '||185.87.50.147^',
  1294. '||10root25.website^', '||24video.xxx^',
  1295. '||adlabs.ru^', '||adspayformymortgage.win^', '||aliru1.ru^', '||amgload.net^', '||aviabay.ru^',
  1296. '||bgrndi.com^', '||brokeloy.com^',
  1297. '||cdnjs-aws.ru^', '||cnamerutor.ru^',
  1298. '||directadvert.ru^', '||docfilms.info^', '||dreadfula.ru^', '||dsn-fishki.ru^',
  1299. '||et-cod.com^', '||et-code.ru^', '||etcodes.com^',
  1300. '||film-doma.ru^',
  1301. '||free-torrent.org^', '||free-torrent.pw^',
  1302. '||free-torrents.org^', '||free-torrents.pw^',
  1303. '||game-torrent.info^', '||gocdn.ru^',
  1304. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  1305. '||kinotochka.net^', '||kinott.com^', '||kinott.ru^',
  1306. '||klcheck.com^', '||kuveres.com^',
  1307. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  1308. '||marketgid.com^', '||mebablo.com^', '||mixadvert.com^', '||mxtads.com^',
  1309. '||nickhel.com^',
  1310. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  1311. '||pigiuqproxy.com^', '||piguiqproxy.com^', '||pkpojhc.com^',
  1312. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  1313. '||rcdn.pro^', '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  1314. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  1315. '||skidl.ru^', '||smi2.net^', '||smcheck.org^',
  1316. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||trustjs.net^', '||ttarget.ru^',
  1317. '||u-dot-id-adtool.appspot.com^', '||utarget.ru^',
  1318. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  1319. '||xxuhter.ru^',
  1320. '||yuiout.online^',
  1321. '||zmctrack.net^', '||zoom-film.ru^'
  1322. ])
  1323. masks.push(new RegExp(
  1324. filter.replace(/([\\/[\].+?(){}$])/g, '\\$1')
  1325. .replace(/\*/g, '.*?')
  1326. .replace(/\^(?!$)/g, '\\.?[^\\w%._-]')
  1327. .replace(/\^$/, '\\.?([^\\w%._-]|$)')
  1328. .replace(/^\|\|/, '^((ws|http)s?:|/)/+([^/.]+\\.)*?'),
  1329. 'i'));
  1330. // main script
  1331. deepWrapAPI(root => {
  1332. const
  1333. _defineProperty = root.Object.defineProperty,
  1334. _getOwnPropertyDescriptor = root.Object.getOwnPropertyDescriptor,
  1335. _dispatchEvent = _bindCall(root.EventTarget.prototype.dispatchEvent);
  1336.  
  1337. const dispatchCustomEvent = (
  1338. target, name, opts = {
  1339. bubble: false,
  1340. cancelable: false
  1341. }
  1342. ) => _dispatchEvent(target, new CustomEvent(name, opts));
  1343.  
  1344. {
  1345. // 'onerror' handler for scripts from blacklisted sources
  1346. const scriptMap = new WeakMap();
  1347. const _HTMLScriptElement = root.HTMLScriptElement,
  1348. _HTMLImageElement = root.HTMLImageElement;
  1349. const _get_tagName = _bindCall(_getOwnPropertyDescriptor(root.Element.prototype, 'tagName').get),
  1350. _get_scr_src = _bindCall(_getOwnPropertyDescriptor(_HTMLScriptElement.prototype, 'src').get),
  1351. _get_img_src = _bindCall(_getOwnPropertyDescriptor(_HTMLImageElement.prototype, 'src').get);
  1352. const _get_src = node => {
  1353. if (node instanceof _HTMLScriptElement)
  1354. return _get_scr_src(node);
  1355. if (node instanceof _HTMLImageElement)
  1356. return _get_img_src(node);
  1357. return undefined;
  1358. };
  1359. const _onerror = _getOwnPropertyDescriptor(root.HTMLElement.prototype, 'onerror'),
  1360. _set_onerror = _bindCall(_onerror.set);
  1361. _onerror.get = function () {
  1362. return scriptMap.get(this) || null;
  1363. };
  1364. _onerror.set = function (callback) {
  1365. if (typeof callback !== 'function') {
  1366. scriptMap.delete(this);
  1367. _set_onerror(this, callback);
  1368. return;
  1369. }
  1370. scriptMap.set(this, callback);
  1371. _set_onerror(this, function () {
  1372. let src = _get_src(this);
  1373. if (isBlocked(src)) {
  1374. _console.trace(`Blocked "onerror" callback from ${_get_tagName(this)}: ${src}`);
  1375. return;
  1376. }
  1377. _apply(scriptMap.get(this), this, arguments);
  1378. });
  1379. };
  1380. _defineProperty(root.HTMLElement.prototype, 'onerror', _onerror);
  1381. }
  1382. // Simplistic WebSocket wrapper for Maxthon and Firefox before v58
  1383. // once again seems required in Google Chrome and similar browsers due to zmctrack.net -_-
  1384. if (_getOwnPropertyDescriptor(root, 'WebSocket'))
  1385. root.WebSocket = new Proxy(root.WebSocket, {
  1386. construct(ws, args) {
  1387. if (isBlocked(args[0])) {
  1388. _console.log('Blocked WS connection:', args[0]);
  1389. return {};
  1390. }
  1391. return _construct(ws, args);
  1392. }
  1393. });
  1394. // Block popular method to open a new window in Google Chrome by dispatching a custom click
  1395. // event on a newly created anchor with _blank target. Untrusted events must not open new windows.
  1396. const clickWhitelist = /^([^.]\.)*?nakarte\.me$/;
  1397. root.EventTarget.prototype.dispatchEvent = new Proxy(root.EventTarget.prototype.dispatchEvent, {
  1398. apply(fun, that, args) {
  1399. const e = args[0];
  1400. if (!clickWhitelist.test(win.location.hostname) &&
  1401. !e.isTrusted && e.type === 'click' && e.constructor.name === 'MouseEvent' &&
  1402. !that.parentNode && that.tagName === 'A' && that.target[0] === '_') {
  1403. _console.log('Blocked dispatching a click event on a parentless anchor:', that);
  1404. return;
  1405. }
  1406. return _apply(fun, that, args);
  1407. }
  1408. });
  1409. // blacklist of domains where all third-party requests are ignored
  1410. const ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1411. // highly suspicious URLs
  1412. const suspicious = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\//i;
  1413. const on_get_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9/]{40,}|[a-z0-9]{8,}|ad\/banner\/.+|show\/\?\d+=\d+&.+)$/i;
  1414. const on_post_ban = /^(https?:)?\/\/(?!(rutube|shazoo|worldoftanks)\.ru[:/])(csp-)?([a-z0-9]{6}){1,2}\.ru\/([a-z0-9]{6,})$/i;
  1415. const yandex_direct = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/(images\/[a-z0-9/_-]{40,}|jstracer?|j?clck\/.*|set\/s\/rsya-tag-users\/data(\?.*)?|static\/main\.js(\?.*)?)$/i;
  1416. const more_y_direct = /^(https?:)?\/\/((([^.]+\.)??(24smi\.org|(echo\.msk|drive2|kakprosto|razlozhi)\.ru)\/(.{290,}|[a-z0-9/_-]{100,}))|yastatic\.net\/.*?\/chunks\/promo\/.*)$/i;
  1417. const whitelist = /^(https?:)?\/\/yandex\.ru\/yobject$/;
  1418. const fabPatterns = /\/fuckadblock/i;
  1419.  
  1420. const blockedUrls = new Set();
  1421.  
  1422. function checkRequest(fname, method, url) {
  1423. let block = isBlocked(url) ||
  1424. ondomains.test(location.hostname) && !ondomains.test(url) ||
  1425. method !== 'POST' && on_get_ban.test(url) ||
  1426. method === 'POST' && on_post_ban.test(url) ||
  1427. yandex_direct.test(url) || more_y_direct.test(url);
  1428. let allow = block && whitelist.test(url) ||
  1429. // Fix for infinite load on Yandex Images: find image, open "other sizes and similar images" in a new tab, click on a preview of a similar image
  1430. (block && method === 'script.src' &&
  1431. root.location.pathname === '/images/search' && root.location.hostname.startsWith('yandex.') &&
  1432. url.startsWith('http') && url.includes('/images/')) || // Direct URLs are similar, but don't have protocol for some reason
  1433. (block && root.location.hostname === 'widgets.kinopoisk.ru' && url.includes('/static/main.js?')) ||
  1434. (block && !url.startsWith('http') && // drive2.ru hid a little CSS style in their requests which shows page content like this
  1435. (root.location.hostname === 'drive2.ru' || root.location.hostname.endsWith('.drive2.ru')));
  1436. if (allow) {
  1437. block = false;
  1438. _console.trace(`Allowed ${fname} ${method} request %o from %o`, url, root.location.href);
  1439. }
  1440. if (block) {
  1441. if (!blockedUrls.has(url)) // don't repeat log if the same URL were blocked more than once
  1442. _console.trace(`Blocked ${fname} ${method} request %o from %o`, url, root.location.href);
  1443. blockedUrls.add(url);
  1444. return true;
  1445. }
  1446. if (!allow && suspicious.test(url))
  1447. _console.trace(`Suspicious ${fname} ${method} request %o from %o`, url, root.location.href);
  1448. return false;
  1449. }
  1450.  
  1451. // workaround for broken searchbar on market.yandex.ru
  1452. const checkOnloadEvent = location.hostname.startsWith('market.yandex.');
  1453. const triggerLoadEvent = /^(https?:)?\/\/([^.]+\.)??yandex(\.[a-z]{2,3}){1,2}\/(j?clck\/.*)$/i;
  1454.  
  1455. // XHR Wrapper
  1456. const _proto = root.XMLHttpRequest && root.XMLHttpRequest.prototype;
  1457. if (_proto) {
  1458. const xhrStopList = new WeakSet();
  1459. const xhrDispatchLoadList = new WeakSet();
  1460. _proto.open = new Proxy(_proto.open, {
  1461. apply(fun, that, args) {
  1462. if (checkOnloadEvent && triggerLoadEvent.test(args[1]))
  1463. xhrDispatchLoadList.add(that);
  1464. if (checkRequest('xhr', ...args)) {
  1465. xhrStopList.add(that);
  1466. return;
  1467. }
  1468. return _apply(fun, that, args);
  1469. }
  1470. });
  1471. if (win.location.hostname.endsWith('.ukr.net') ||
  1472. win.location.hostname === 'ukr.net') {
  1473. // Technically useless code, but zmctrack's code on ukr.net runs before mine for some reason and is
  1474. // looking for 'skip_xhr_check' in this particular function's code and changes own behaviour
  1475. // depending on this... and somehow cease to work. Well, let it be here then for now.
  1476. const _open = _bindCall(_proto.open);
  1477. _proto.open = function open(...args) {
  1478. return _open(this, ...args); /*skip_xhr_check*/
  1479. };
  1480. }
  1481. const _DONE = _proto.DONE; // 4
  1482. const sendWrapper = {
  1483. apply(fun, that, args) {
  1484. if (xhrStopList.has(that)) {
  1485. if (that.readyState !== _DONE && xhrDispatchLoadList.has(that)) {
  1486. that.readyState = _DONE;
  1487. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1488. }
  1489. return null;
  1490. }
  1491. return _apply(fun, that, args);
  1492. }
  1493. };
  1494. ['send', 'setRequestHeader', 'getAllResponseHeaders'].forEach(
  1495. name => _proto[name] = new Proxy(_proto[name], sendWrapper)
  1496. );
  1497. // simulate readyState === 1 for blocked requests
  1498. const _readyState = Object.getOwnPropertyDescriptor(_proto, 'readyState');
  1499. _readyState.get = new Proxy(_readyState.get, {
  1500. apply(fun, that, args) {
  1501. return xhrStopList.has(that) ? 1 : _apply(fun, that, args);
  1502. }
  1503. });
  1504. Object.defineProperty(_proto, 'readyState', _readyState);
  1505. }
  1506.  
  1507. if (root.fetch)
  1508. root.fetch = new Proxy(root.fetch, {
  1509. apply(fun, that, args) {
  1510. let [url, opts] = args;
  1511. let method = opts && opts.method || 'GET';
  1512. if (typeof url === 'object' && 'headers' in url &&
  1513. 'url' in url && 'method' in url) // url instanceof Request
  1514. ({
  1515. url,
  1516. method
  1517. } = url);
  1518. if (checkRequest('fetch', method, url))
  1519. return new Promise(() => null);
  1520. return _apply(fun, that, args);
  1521. }
  1522. });
  1523.  
  1524. const _script_src = Object.getOwnPropertyDescriptor(root.HTMLScriptElement.prototype, 'src');
  1525. _script_src.set = new Proxy(_script_src.set, {
  1526. apply(fun, that, args) {
  1527. if (fabPatterns.test(args[0])) {
  1528. _console.trace('Blocked set script.src request:', args[0]);
  1529. deployFABStub(root);
  1530. setTimeout(() => dispatchCustomEvent(that, 'load'), 0);
  1531. return;
  1532. }
  1533. return checkRequest('set', 'script.src', args[0]) || _apply(fun, that, args);
  1534. }
  1535. });
  1536. Object.defineProperty(root.HTMLScriptElement.prototype, 'src', _script_src);
  1537.  
  1538. const adregain_pattern = /ggg==" alt="advertisement"/;
  1539. if (root.self !== root.top) // in IFrame
  1540. root.document.write = new Proxy(root.document.write, {
  1541. apply(fun, that, args) {
  1542. if (adregain_pattern.test(args[0])) {
  1543. _console.log('Skipped AdRegain frame.');
  1544. args[0] = '';
  1545. }
  1546. return _apply(fun, that, args);
  1547. }
  1548. });
  1549. });
  1550. }, deepWrapAPI
  1551. );
  1552.  
  1553. // === Helper functions ===
  1554.  
  1555. // function to search and remove nodes by content
  1556. // selector - standard CSS selector to define set of nodes to check
  1557. // words - regular expression to check content of the suspicious nodes
  1558. // params - object with multiple extra parameters:
  1559. // .log - display log in the console
  1560. // .hide - set display to none instead of removing from the page
  1561. // .parent - parent node to remove if content is found in the child node
  1562. // .siblings - number of simling nodes to remove (excluding text nodes)
  1563. function scissors(selector, words, scope, params) {
  1564. const logger = (...args) => {
  1565. if (params.log) _console.log(...args);
  1566. };
  1567. const scHide = node => {
  1568. let style = _getAttribute(node, 'style') || '',
  1569. hide = ';display:none!important;';
  1570. if (style.indexOf(hide) < 0)
  1571. _setAttribute(node, 'style', style + hide);
  1572. };
  1573.  
  1574. if (!scope.contains(_document.body))
  1575. logger('[s] scope', scope);
  1576. let remFunc = (params.hide ? scHide : node => node.parentNode.removeChild(node)),
  1577. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1578. toRemove = [],
  1579. siblings;
  1580. for (let node of scope.querySelectorAll(selector)) {
  1581. // drill up to a parent node if specified, break if not found
  1582. if (params.parent) {
  1583. let old = node;
  1584. node = node.closest(params.parent);
  1585. if (node === null || node.contains(scope)) {
  1586. logger('[s] went out of scope with', old);
  1587. continue;
  1588. }
  1589. }
  1590. logger('[s] processing', node);
  1591. if (toRemove.includes(node))
  1592. continue;
  1593. if (words.test(node.innerHTML)) {
  1594. // skip node if already marked for removal
  1595. logger('[s] marked for removal');
  1596. toRemove.push(node);
  1597. // add multiple nodes if defined more than one sibling
  1598. siblings = Math.abs(params.siblings) || 0;
  1599. while (siblings) {
  1600. node = node[iterFunc];
  1601. if (!node) break; // can't go any further - exit
  1602. logger('[s] adding sibling node', node);
  1603. toRemove.push(node);
  1604. siblings -= 1;
  1605. }
  1606. }
  1607. }
  1608. const toSkip = [];
  1609. toSkip.checkNode = node => !toRemove.every(other => other === node || !node.contains(other));
  1610. for (let node of toRemove)
  1611. if (toSkip.checkNode(node))
  1612. toSkip.push(node);
  1613. if (toRemove.length)
  1614. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1615. for (let node of toRemove)
  1616. if (!toSkip.includes(node))
  1617. remFunc(node);
  1618. }
  1619.  
  1620. // function to perform multiple checks if ads inserted with a delay
  1621. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1622. // also does 1 extra check when a page completely loads
  1623. // selector and words - passed dow to scissors
  1624. // params - object with multiple extra parameters:
  1625. // .log - display log in the console
  1626. // .root - selector to narrow down scope to scan;
  1627. // .observe - if true then check will be performed continuously;
  1628. // Other parameters passed down to scissors.
  1629. function gardener(selector, words, params) {
  1630. let logger = (...args) => {
  1631. if (params.log) _console.log(...args);
  1632. };
  1633. params = params || {};
  1634. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1635. let scope;
  1636. let globalScope = [_de];
  1637. let domLoaded = false;
  1638. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1639. let onevent = e => {
  1640. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1641. for (let node of scope)
  1642. scissors(selector, words, node, params);
  1643. };
  1644. let repeater = n => {
  1645. if (!domLoaded && n) {
  1646. setTimeout(repeater, 500, n - 1);
  1647. scope = getScope(params.root);
  1648. if (!scope) // exit if the root element is not present on the page
  1649. return 0;
  1650. onevent({
  1651. type: 'Repeater'
  1652. });
  1653. }
  1654. };
  1655. repeater(20);
  1656. _document.addEventListener(
  1657. 'DOMContentLoaded', (e) => {
  1658. domLoaded = true;
  1659. // narrow down scope to a specific element
  1660. scope = getScope(params.root);
  1661. if (!scope) // exit if the root element is not present on the page
  1662. return 0;
  1663. logger('[g] scope', scope);
  1664. // add observe mode if required
  1665. if (params.observe) {
  1666. let params = {
  1667. childList: true,
  1668. subtree: true
  1669. };
  1670. let observer = new MutationObserver(
  1671. function (ms) {
  1672. for (let m of ms)
  1673. if (m.addedNodes.length)
  1674. onevent(m);
  1675. }
  1676. );
  1677. for (let node of scope)
  1678. observer.observe(node, params);
  1679. logger('[g] observer enabled');
  1680. }
  1681. onevent(e);
  1682. }, false);
  1683. // wait for a full page load to do one extra cut
  1684. win.addEventListener('load', onevent, false);
  1685. }
  1686.  
  1687. // wrap popular methods to open a new tab to catch specific behaviours
  1688. function createWindowOpenWrapper(openFunc) {
  1689. const parser = _createElement('a');
  1690. const openWhitelist = (url, parent) => {
  1691. parser.href = url;
  1692. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru' ||
  1693. parent.hostname === 'radikal.ru' && url === undefined;
  1694. };
  1695.  
  1696. function redefineOpen(root) {
  1697. if ('open' in root)
  1698. root.open = new Proxy(root.open, {
  1699. apply(fun, that, args) {
  1700. if (openWhitelist(args[0], location)) {
  1701. _console.log('Whitelisted popup:', ...args);
  1702. return _apply(fun, that, args);
  1703. }
  1704. return openFunc(...args);
  1705. }
  1706. });
  1707. }
  1708. redefineOpen(win);
  1709.  
  1710. const createElementWrapper = {
  1711. apply(fun, that, args) {
  1712. const el = _apply(fun, that, args);
  1713. // redefine window.open in first-party frames
  1714. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  1715. el.addEventListener('load', (e) => {
  1716. try {
  1717. redefineOpen(e.target.contentWindow);
  1718. } catch (ignore) {}
  1719. }, false);
  1720. return el;
  1721. }
  1722. };
  1723.  
  1724. function redefineCreateElement(obj) {
  1725. for (let root of [obj.document, _Document])
  1726. if ('createElement' in root) {
  1727. root.createElement = new Proxy(root.createElement, createElementWrapper);
  1728. nt.defineOn(root, 'createElement', new Proxy(createElement, {}), 'Document.prototype.');
  1729. }
  1730. }
  1731. redefineCreateElement(win);
  1732.  
  1733. // wrap window.open in newly added first-party frames
  1734. _Element.appendChild = new Proxy(_Element.appendChild, {
  1735. apply(fun, that, args) {
  1736. let el = _apply(fun, that, args);
  1737. if (el instanceof HTMLIFrameElement)
  1738. try {
  1739. redefineOpen(el.contentWindow);
  1740. redefineCreateElement(el.contentWindow);
  1741. } catch (ignore) {}
  1742. return el;
  1743. }
  1744. });
  1745. }
  1746.  
  1747. // Function to catch and block various methods to open a new window with 3rd-party content.
  1748. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  1749. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  1750. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  1751. // node or simply a link with piece of javascript code in the HREF attribute.
  1752. function preventPopups() {
  1753. // call sandbox-me if in iframe and not whitelisted
  1754. if (inIFrame) {
  1755. win.top.postMessage({
  1756. name: 'sandbox-me',
  1757. href: win.location.href
  1758. }, '*');
  1759. return;
  1760. }
  1761.  
  1762. scriptLander(() => {
  1763. let open = (...args) => {
  1764. '[native code]';
  1765. _console.trace('Site attempted to open a new window', ...args);
  1766. return {
  1767. document: nt.proxy({
  1768. write: nt.func({}, 'write'),
  1769. writeln: nt.func({}, 'writeln')
  1770. }),
  1771. location: nt.proxy({})
  1772. };
  1773. };
  1774.  
  1775. createWindowOpenWrapper(open);
  1776.  
  1777. _console.log('Popup prevention enabled.');
  1778. }, nullTools, createWindowOpenWrapper);
  1779. }
  1780.  
  1781. // Helper function to close background tab if site opens itself in a new tab and then
  1782. // loads a 3rd-party page in the background one (thus performing background redirect).
  1783. function preventPopunders() {
  1784. // create "close_me" event to call high-level window.close()
  1785. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1786. let callClose = () => {
  1787. _console.log('close call');
  1788. window.close();
  1789. };
  1790. window.addEventListener(eventName, callClose, true);
  1791.  
  1792. scriptLander(() => {
  1793. // get host of a provided URL with help of an anchor object
  1794. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1795. let parseURL = _document.createElement('A');
  1796. let getHost = url => {
  1797. parseURL.href = url;
  1798. return parseURL.hostname;
  1799. };
  1800. // site went to a new tab and attempts to unload
  1801. // call for high-level close through event
  1802. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  1803. // check is URL local or goes to different site
  1804. let isLocal = (url) => {
  1805. if (url === location.pathname || url === location.href)
  1806. return true; // URL points to current pathname or full address
  1807. let host = getHost(url);
  1808. let site = location.hostname;
  1809. return host !== '' && // URLs with unusual protocol may have empty 'host'
  1810. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  1811. };
  1812.  
  1813. let _open = window.open.bind(window);
  1814. let open = (...args) => {
  1815. '[native code]';
  1816. let url = args[0];
  1817. if (url && isLocal(url))
  1818. window.addEventListener('beforeunload', closeWindow, true);
  1819. return _open(...args);
  1820. };
  1821.  
  1822. createWindowOpenWrapper(open);
  1823.  
  1824. _console.log("Background redirect prevention enabled.");
  1825. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  1826. }
  1827.  
  1828. // Mix between check for popups and popunders
  1829. // Significantly more agressive than both and can't be used as universal solution
  1830. function preventPopMix() {
  1831. if (inIFrame) {
  1832. win.top.postMessage({
  1833. name: 'sandbox-me',
  1834. href: win.location.href
  1835. }, '*');
  1836. return;
  1837. }
  1838.  
  1839. // create "close_me" event to call high-level window.close()
  1840. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  1841. let callClose = () => {
  1842. _console.log('close call');
  1843. window.close();
  1844. };
  1845. window.addEventListener(eventName, callClose, true);
  1846.  
  1847. scriptLander(() => {
  1848. let _open = window.open,
  1849. parseURL = _document.createElement('A');
  1850. // get host of a provided URL with help of an anchor object
  1851. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  1852. let getHost = (url) => {
  1853. parseURL.href = url;
  1854. return parseURL.host;
  1855. };
  1856. // site went to a new tab and attempts to unload
  1857. // call for high-level close through event
  1858. let closeWindow = () => {
  1859. _open(window.location, '_self');
  1860. window.dispatchEvent(new CustomEvent(eventName, {}));
  1861. };
  1862. // check is URL local or goes to different site
  1863. function isLocal(url) {
  1864. let loc = window.location;
  1865. if (url === loc.pathname || url === loc.href)
  1866. return true; // URL points to current pathname or full address
  1867. let host = getHost(url),
  1868. site = loc.host;
  1869. if (host === '')
  1870. return false; // URLs with unusual protocol may have empty 'host'
  1871. if (host.length > site.length)
  1872. [site, host] = [host, site];
  1873. return site.includes(host, site.length - host.length);
  1874. }
  1875.  
  1876. // add check for redirect for 5 seconds, then disable it
  1877. function checkRedirect() {
  1878. window.addEventListener('beforeunload', closeWindow, true);
  1879. setTimeout(closeWindow => window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  1880. }
  1881.  
  1882. function open(url, name) {
  1883. '[native code]';
  1884. if (url && isLocal(url) && (!name || name === '_blank')) {
  1885. _console.trace('Suspicious local new window', ...arguments);
  1886. checkRedirect();
  1887. /* jshint validthis: true */
  1888. return _open.apply(this, arguments);
  1889. }
  1890. _console.trace('Blocked attempt to open a new window', ...arguments);
  1891. return {
  1892. document: {
  1893. write() {},
  1894. writeln() {}
  1895. }
  1896. };
  1897. }
  1898.  
  1899. function clickHandler(e) {
  1900. let link = e.target,
  1901. url = link.href || '';
  1902. if (e.targetParentNode && e.isTrusted || link.target !== '_blank') {
  1903. _console.log('Link', link, 'were created dinamically, but looks fine.');
  1904. return true;
  1905. }
  1906. if (isLocal(url) && link.target === '_blank') {
  1907. _console.log('Suspicious local link', link);
  1908. checkRedirect();
  1909. return;
  1910. }
  1911. _console.log('Blocked suspicious click on a link', link);
  1912. e.stopPropagation();
  1913. e.preventDefault();
  1914. }
  1915.  
  1916. createWindowOpenWrapper(open, clickHandler);
  1917.  
  1918. _console.log("Mixed popups prevention enabled.");
  1919. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  1920. }
  1921. // External listener for case when site known to open popups were loaded in iframe
  1922. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  1923. // Some sites replace frame's window.location with data-url to run in clean context
  1924. if (!inIFrame) window.addEventListener(
  1925. 'message',
  1926. function (e) {
  1927. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  1928. return;
  1929. let src = e.data.href;
  1930. for (let frame of _document.querySelectorAll('iframe'))
  1931. if (frame.contentWindow === e.source) {
  1932. if (frame.hasAttribute('sandbox')) {
  1933. if (!frame.sandbox.contains('allow-popups'))
  1934. return; // exit frame since it's already sandboxed and popups are blocked
  1935. // remove allow-popups if frame already sandboxed
  1936. frame.sandbox.remove('allow-popups');
  1937. } else
  1938. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  1939. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  1940. // but to apply content must be reloaded and this script will re-apply it in the result
  1941. frame.setAttribute('sandbox', 'allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  1942. _console.log('Disallowed popups from iframe', frame);
  1943.  
  1944. // reload frame content to apply restrictions
  1945. if (!src) {
  1946. src = frame.src;
  1947. _console.log('Unable to get current iframe location, reloading from src', src);
  1948. } else
  1949. _console.log('Reloading iframe with URL', src);
  1950. frame.src = 'about:blank';
  1951. frame.src = src;
  1952. }
  1953. }, false
  1954. );
  1955.  
  1956. const evalPatternYandex = /{exports:{},id:r,loaded:!1}|containerId:(.|\r|\n)+params:/,
  1957. evalPatternGeneric = /_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i;
  1958.  
  1959. function selectiveEval(...patterns) {
  1960. let fullLog = false;
  1961. if (patterns[patterns.length - 1] === true) {
  1962. fullLog = true;
  1963. patterns.length = patterns.length - 1;
  1964. }
  1965. if (patterns.length === 0)
  1966. patterns.push(evalPatternGeneric);
  1967. win.eval = new Proxy(win.eval, {
  1968. apply(fun, that, args) {
  1969. if (patterns.some(pattern => pattern.test(args[0]))) {
  1970. _console[fullLog ? 'trace' : 'log'](`Skipped eval ${fullLog ? args[0] : args[0].slice(0, 512)}${fullLog ? '' : '\u2026'}`);
  1971. return null;
  1972. }
  1973. try {
  1974. if (fullLog)
  1975. _console.trace(`eval ${args[0]}`);
  1976. return _apply(fun, that, args);
  1977. } catch (e) {
  1978. _console.error('Crash source:', args[0]);
  1979. throw e;
  1980. }
  1981. }
  1982. });
  1983. }
  1984. selectiveEval.toString = new Proxy(selectiveEval.toString, {
  1985. apply(...args) {
  1986. return `${_apply(...args)} const evalPatternYandex = ${evalPatternYandex}, evalPatternGeneric = ${evalPatternGeneric}`;
  1987. }
  1988. });
  1989.  
  1990. // hides cookies by pattern and attempts to remove them if they already set
  1991. // also prevents setting new versions of such cookies
  1992. function selectiveCookies(scPattern = '', opts = {}) {
  1993. let patterns = scPattern.split('|');
  1994. if (patterns[0] !== '~default') {
  1995. // Google Analytics cookies
  1996. patterns.push('_g(at?|id)|__utm[a-z]');
  1997. // Yandex ABP detection cookies
  1998. patterns.push('bltsr|blcrm');
  1999. } else
  2000. patterns.shift();
  2001. let blacklist = new RegExp(`(^|;\\s?)(${patterns.join('|')})($|=)`);
  2002.  
  2003. const root = opts.root || win;
  2004. const _root_Document = Object.getPrototypeOf(root.HTMLDocument.prototype);
  2005. const _doc_proto = ('cookie' in _root_Document) ? _root_Document : Object.getPrototypeOf(root.document);
  2006. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  2007. const _set_cookie = _bindCall(_cookie.set);
  2008.  
  2009. const removeLog = (cookie) => {
  2010. let strings = [`${cookie.name}=${cookie.value}`];
  2011. if (cookie.domain)
  2012. strings.push(`domain=${cookie.domain}`);
  2013. if (cookie.path)
  2014. strings.push(`path=${cookie.path}`);
  2015. if (cookie.sameSite !== 'unspecified')
  2016. strings.push(`sameSite=${cookie.sameSite}`);
  2017. for (let name of ['httpOnly', 'hostOnly', 'secure', 'session'])
  2018. if (cookie[name]) strings.push(name);
  2019. _console.log(`Removed cookie: ${strings.join('; ')}`);
  2020. };
  2021.  
  2022. let skipTM = true;
  2023. const asyncCookieCleaner = () => {
  2024. GM.cookie.list({
  2025. url: location.href
  2026. }).then(cookies => {
  2027. if (!cookies) return;
  2028. if (skipTM) {
  2029. cookies = cookies.filter(x => !x.name.startsWith('TM_'));
  2030. skipTM = false;
  2031. }
  2032. for (let cookie of cookies)
  2033. if (blacklist.test(cookie.name)) {
  2034. if (skipTM && cookie.name)
  2035. continue;
  2036. GM.cookie.delete(cookie);
  2037. removeLog(cookie);
  2038. }
  2039. });
  2040. };
  2041.  
  2042. const useOldPass = (() => {
  2043. // returns true if GM version <= 4.10
  2044. let v = GM.info.version.split('.').map(x => x - 0);
  2045. return v[0] < 4 || v[0] === 4 && v[1] <= 10 && v[2] === undefined || GM.info.scriptHandler !== 'Tampermonkey';
  2046. })();
  2047.  
  2048. const getName = (cookie) => cookie && cookie.indexOf('=') ? /^(.+?)=/.exec(cookie)[1] : cookie;
  2049.  
  2050. const removeCookie = (cookie, that) => {
  2051. const expireCookie = (name, domain) => {
  2052. domain = domain ? `;domain=${domain.join('.')}` : '';
  2053. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain}`);
  2054. _set_cookie(that, `${name}=;Max-Age=0;path=/${domain.replace('=', '=.')}`);
  2055. };
  2056. const name = getName(cookie);
  2057. const domain = that.location.hostname.split('.');
  2058.  
  2059. expireCookie(name);
  2060. while (domain.length > 1) {
  2061. try {
  2062. expireCookie(name, domain);
  2063. } catch (e) {
  2064. _console.error(e);
  2065. }
  2066. domain.shift();
  2067. }
  2068. _console.log('Removing existing cookie:', cookie);
  2069. };
  2070.  
  2071. if (_cookie) {
  2072. // skip setting unwanted cookies
  2073. _cookie.set = new Proxy(_cookie.set, {
  2074. apply(fun, that, args) {
  2075. if (useOldPass) {
  2076. let cookie = args[0];
  2077. if (blacklist.test(getName(cookie))) {
  2078. _console.log('Ignored cookie: %s', cookie);
  2079. removeCookie(cookie, that);
  2080. return;
  2081. }
  2082. }
  2083. _apply(fun, that, args);
  2084. asyncCookieCleaner();
  2085. return true;
  2086. }
  2087. });
  2088. // hide unwanted cookies from site
  2089. _cookie.get = new Proxy(_cookie.get, {
  2090. apply(fun, that, args) {
  2091. asyncCookieCleaner();
  2092. let res = _apply(fun, that, args);
  2093. if (blacklist.test(res)) {
  2094. let stack = [];
  2095. for (let cookie of res.split(/;\s?/))
  2096. if (!blacklist.test(getName(cookie)))
  2097. stack.push(cookie);
  2098. else
  2099. if (useOldPass) removeCookie(cookie, that);
  2100. res = stack.join('; ');
  2101. }
  2102. return res;
  2103. }
  2104. });
  2105. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  2106. _console.log('Active cookies:', root.document.cookie);
  2107. }
  2108. }
  2109.  
  2110. // Locates a node with specific text in Russian
  2111. // Uses table of substitutions for similar letters
  2112. let selectNodeByTextContent = (() => {
  2113. let subs = {
  2114. // english & greek
  2115. 'А': 'AΑ',
  2116. 'В': 'BΒ',
  2117. 'Г': 'Γ',
  2118. 'Е': 'EΕ',
  2119. 'З': '3',
  2120. 'К': 'KΚ',
  2121. 'М': 'MΜ',
  2122. 'Н': 'HΗ',
  2123. 'О': 'OΟ',
  2124. 'П': 'Π',
  2125. 'Р': 'PΡ',
  2126. 'С': 'C',
  2127. 'Т': 'T',
  2128. 'Ф': 'Φ',
  2129. 'Х': 'XΧ'
  2130. };
  2131. let regExpBuilder = text => new RegExp(
  2132. text.toUpperCase()
  2133. .split('')
  2134. .map(function (e) {
  2135. return `${e in subs ? `[${e}${subs[e]}]` : (e === ' ' ? '\\s+' : e)}[\u200b\u200c\u200d]*`;
  2136. })
  2137. .join(''),
  2138. 'i');
  2139. let reMap = {};
  2140. return (re, opts = {
  2141. root: _document.body
  2142. }) => {
  2143. if (!re.test) {
  2144. if (!reMap[re])
  2145. reMap[re] = regExpBuilder(re);
  2146. re = reMap[re];
  2147. }
  2148.  
  2149. for (let child of opts.root.children)
  2150. if (re.test(child.textContent)) {
  2151. if (opts.shallow)
  2152. return child;
  2153. opts.root = child;
  2154. return selectNodeByTextContent(re, opts) || child;
  2155. }
  2156. };
  2157. })();
  2158.  
  2159. // webpackJsonp filter
  2160. function webpackJsonpFilter(blacklist, log = false) {
  2161. function wrapPush(webpack) {
  2162. let _push = webpack.push.bind(webpack);
  2163. Object.defineProperty(webpack, 'push', {
  2164. get() {
  2165. return _push;
  2166. },
  2167. set(vl) {
  2168. _push = new Proxy(vl, {
  2169. apply(fun, that, args) {
  2170. wrapper: {
  2171. if (!(args[0] instanceof Array))
  2172. break wrapper;
  2173. let mainName;
  2174. if (args[0][2] instanceof Array && args[0][2][0] instanceof Array)
  2175. mainName = args[0][2][0][0];
  2176. let funs = args[0][1];
  2177. if (!(funs instanceof Object && !(funs instanceof Array)))
  2178. break wrapper;
  2179. const noopFunc = (name, text) => () => _console.log(`Skip webpack ${name}`, text);
  2180. for (let name in funs) {
  2181. if (typeof funs[name] !== 'function')
  2182. continue;
  2183. if (blacklist.test(_toString(funs[name])) && name !== mainName)
  2184. funs[name] = noopFunc(name, log ? _toString(funs[name]) : '');
  2185. }
  2186. }
  2187. _console.log('webpack.push()');
  2188. return _apply(fun, that, args);
  2189. }
  2190. });
  2191. return true;
  2192. }
  2193. });
  2194. return webpack;
  2195. }
  2196. let _webpackJsonp = wrapPush([]);
  2197. Object.defineProperty(win, 'webpackJsonp', {
  2198. get() {
  2199. return _webpackJsonp;
  2200. },
  2201. set(vl) {
  2202. if (vl === _webpackJsonp)
  2203. return;
  2204. _console.log('new webpackJsonp', vl);
  2205. _webpackJsonp = wrapPush(vl);
  2206. }
  2207. });
  2208. }
  2209.  
  2210. // JSON filter
  2211. // removeList - list of paths divided by space to remove
  2212. // checkList - optional list of paths divided by space to check presence of before removal
  2213. const jsonFilter = (function jsonFilterModule() {
  2214. const _log = (() => {
  2215. if (!jsf.AccessStatistics)
  2216. return () => null;
  2217. const counter = {};
  2218. const counterToString = () => Object.entries(counter).map(a => `\n * ${a.join(': ')}`).join('');
  2219. let lock = 0;
  2220. return async function _log(path) {
  2221. counter[path] = (counter[path] || 0) + 1;
  2222. lock++;
  2223. setTimeout(() => {
  2224. lock--;
  2225. if (lock === 0)
  2226. _console.log('JSON filters:', counterToString());
  2227. }, 3333);
  2228. };
  2229. })();
  2230.  
  2231. const isObjecty = o => (typeof o === 'object' || typeof o === 'function') && o !== null;
  2232.  
  2233. function parsePath(root, path) {
  2234. let pos;
  2235. pos = path.indexOf('.');
  2236. for (let name; pos > 0;) {
  2237. name = path.slice(0, pos);
  2238. if (!isObjecty(root[name]))
  2239. break;
  2240. root = root[name];
  2241. path = path.slice(pos + 1);
  2242. pos = path.indexOf('.');
  2243. }
  2244. return [pos < 0 && _hasOwnProperty(root, path), root, path];
  2245. }
  2246.  
  2247. const filterList = [];
  2248.  
  2249. function filter(result) {
  2250. if (!isObjecty(result))
  2251. return result;
  2252.  
  2253. const pathNotInObject = path => !(parsePath(result, path)[0]);
  2254. const removePathInObject = path => {
  2255. let [exist, root, name] = parsePath(result, path);
  2256. if (exist) {
  2257. delete root[name];
  2258. _log(path);
  2259. }
  2260. };
  2261. for (let list of filterList) {
  2262. if (list.check && list.check.some(pathNotInObject))
  2263. return result;
  2264. list.remove.forEach(removePathInObject);
  2265. }
  2266.  
  2267. return result;
  2268. }
  2269.  
  2270.  
  2271. let wrapped = false;
  2272.  
  2273. function jsonFilter(removeList, checkList) {
  2274. filterList.push({
  2275. remove: removeList.split(/\s/),
  2276. check: checkList ? checkList.split(/\s/) : undefined
  2277. });
  2278.  
  2279. if (wrapped) return;
  2280. wrapped = true;
  2281.  
  2282. win.JSON.parse = new Proxy(win.JSON.parse, {
  2283. apply(fun, that, args) {
  2284. return filter(_apply(fun, that, args));
  2285. }
  2286. });
  2287.  
  2288. win.Response.prototype.json = new Proxy(win.Response.prototype.json, {
  2289. apply(fun, that, args) {
  2290. let promise = _apply(fun, that, args);
  2291. promise.then(res => filter(res));
  2292. return promise;
  2293. }
  2294. });
  2295. }
  2296. jsonFilter.toString = () => `const jsonFilter = (${jsonFilterModule.toString()})()`;
  2297. return jsonFilter;
  2298. })();
  2299.  
  2300. // === Scripts for specific domains ===
  2301.  
  2302. const scripts = {
  2303. // prevent popups and redirects block
  2304. // Popups
  2305. preventPopups: {
  2306. other: 'biqle.ru, chaturbate.com, dfiles.ru, eporner.eu, hentaiz.org, mirrorcreator.com, online-multy.ru' +
  2307. 'radikal.ru, rumedia.ws, tapehub.tech, thepiratebay.org, unionpeer.com, zippyshare.com',
  2308. now: preventPopups
  2309. },
  2310. // Popunders (background redirect)
  2311. preventPopunders: {
  2312. other: 'lostfilm-online.ru, mediafire.com, megapeer.org, megapeer.ru, perfectgirls.net',
  2313. now: preventPopunders
  2314. },
  2315.  
  2316. // PopMix (both types of popups encountered on site)
  2317. 'openload.co': {
  2318. other: 'oload.tv, oload.info, openload.co.com',
  2319. now() {
  2320. if (inIFrame) {
  2321. nt.define('BetterJsPop', {
  2322. add(a, b) {
  2323. _console.trace('BetterJsPop.add(%o, %o)', a, b);
  2324. },
  2325. config(o) {
  2326. _console.trace('BetterJsPop.config(%o)', o);
  2327. },
  2328. Browser: {
  2329. isChrome: true
  2330. }
  2331. });
  2332. nt.define('isSandboxed', nt.func(null, 'isSandboxed'));
  2333. nt.define('adblock', false);
  2334. nt.define('adblock2', false);
  2335. } else preventPopMix();
  2336. }
  2337. },
  2338.  
  2339. 'turbobit.net': preventPopMix,
  2340.  
  2341. 'tapochek.net': () => {
  2342. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2343. let _appendChild = Object.getOwnPropertyDescriptor(_Node, 'appendChild');
  2344. let _appendChild_value = _appendChild.value;
  2345. _appendChild.value = function appendChild(node) {
  2346. if (this === _document.body)
  2347. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2348. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2349. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2350. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2351. throw '...eenope!';
  2352. return _appendChild_value.apply(this, arguments);
  2353. };
  2354. Object.defineProperty(_Node, 'appendChild', _appendChild);
  2355.  
  2356. // disable window focus tricks and changing location
  2357. let focusHandlerName = /\WfocusAchieved\(/;
  2358. let _setInterval = win.setInterval;
  2359. win.setInterval = (...args) => {
  2360. if (args.length && focusHandlerName.test(_toString(args[0]))) {
  2361. _console.log('skip setInterval for', ...args);
  2362. return -1;
  2363. }
  2364. return _setInterval(...args);
  2365. };
  2366. let _addEventListener = win.addEventListener;
  2367. win.addEventListener = function (...args) {
  2368. if (args.length && args[0] === 'focus' && focusHandlerName.test(_toString(args[1]))) {
  2369. _console.log('skip addEventListener for', ...args);
  2370. return undefined;
  2371. }
  2372. return _addEventListener.apply(this, args);
  2373. };
  2374.  
  2375. // generic popup prevention
  2376. preventPopups();
  2377. },
  2378.  
  2379. // = other ======================================================================================
  2380.  
  2381. '1tv.ru': {
  2382. other: 'mediavitrina.ru',
  2383. now: () => scriptLander(() => {
  2384. nt.define('EUMPAntiblockConfig', nt.proxy({
  2385. url: '//www.1tv.ru/favicon.ico'
  2386. }));
  2387. nt.define('Object.prototype.disableSeek', nt.func(undefined, 'disableSeek'));
  2388. //nt.define('preroll', undefined);
  2389.  
  2390. let _EUMP;
  2391. const _EUMP_set = x => {
  2392. if (x === _EUMP)
  2393. return true;
  2394. let _plugins = x.plugins;
  2395. Object.defineProperty(x, 'plugins', {
  2396. enumerable: true,
  2397. get() {
  2398. return _plugins;
  2399. },
  2400. set(vl) {
  2401. if (vl === _plugins)
  2402. return true;
  2403. nt.defineOn(vl, 'antiblock', function (player, opts) {
  2404. const antiblock = nt.proxy({
  2405. opts: opts,
  2406. readyState: 'ready',
  2407. isEUMPPlugin: true,
  2408. detected: nt.func(false, 'antiblock.detected'),
  2409. currentWeight: nt.func(0, 'antiblock.currentWeight')
  2410. });
  2411. player.antiblock = antiblock;
  2412. return antiblock;
  2413. }, 'EUMP.plugins.');
  2414. _plugins = vl;
  2415. }
  2416. });
  2417. _EUMP = x;
  2418. return true;
  2419. };
  2420. if ('EUMP' in win)
  2421. _EUMP_set(win.EUMP);
  2422. Object.defineProperty(win, 'EUMP', {
  2423. enumerable: true,
  2424. get() {
  2425. return _EUMP;
  2426. },
  2427. set: _EUMP_set
  2428. });
  2429.  
  2430. let _EUMPVGTRK;
  2431. const _EUMPVGTRK_set = x => {
  2432. if (x === _EUMPVGTRK)
  2433. return true;
  2434. if (x && x.prototype) {
  2435. if ('generatePrerollUrls' in x.prototype)
  2436. nt.defineOn(x.prototype, 'generatePrerollUrls', nt.func(null, 'EUMPVGTRK.generatePrerollUrls'), 'EUMPVGTRK.prototype.', {
  2437. enumerable: false
  2438. });
  2439. if ('sendAdsEvent' in x.prototype)
  2440. nt.defineOn(x.prototype, 'sendAdsEvent', nt.func(null, 'EUMPVGTRK.sendAdsEvent'), 'EUMPVGTRK.prototype.', {
  2441. enumerable: false
  2442. });
  2443. }
  2444. _EUMPVGTRK = x;
  2445. return true;
  2446. };
  2447. if ('EUMPVGTRK' in win)
  2448. _EUMPVGTRK_set(win.EUMPVGTRK);
  2449. Object.defineProperty(win, 'EUMPVGTRK', {
  2450. enumerable: true,
  2451. get() {
  2452. return _EUMPVGTRK;
  2453. },
  2454. set: _EUMPVGTRK_set
  2455. });
  2456. }, nullTools)
  2457. },
  2458.  
  2459. '24smi.org': () => scriptLander(() => selectiveCookies('has_adblock'), selectiveCookies),
  2460.  
  2461. '2picsun.ru': {
  2462. other: 'pics2sun.ru, 3pics-img.ru',
  2463. now() {
  2464. Object.defineProperty(navigator, 'userAgent', {
  2465. value: 'googlebot'
  2466. });
  2467. }
  2468. },
  2469.  
  2470. '4pda.ru': {
  2471. now() {
  2472. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2473. const isForum = location.pathname.startsWith('/forum/'),
  2474. remove = node => (node && node.parentNode.removeChild(node)),
  2475. hide = node => (node && (node.style.display = 'none'));
  2476.  
  2477. selectiveCookies('viewpref');
  2478. abortExecution.inlineScript('document.querySelector', {
  2479. pattern: /\(document(,window)?\);/
  2480. });
  2481.  
  2482. function cleaner(log) {
  2483. HeaderAds: {
  2484. // hide ads above HEADER
  2485. let nav = _document.querySelector('.menu-main-item');
  2486. while (nav && (nav.parentNode !== _de))
  2487. if (!nav.parentNode.querySelector('article, .container[itemtype$="Article"]'))
  2488. nav = nav.parentNode;
  2489. else break;
  2490. if (!nav || (nav.parentNode === _de)) {
  2491. if (log) _console.warn('Unable to locate header element');
  2492. break HeaderAds;
  2493. }
  2494. if (log) _console.log('Processing header:', nav);
  2495. for (let itm of nav.parentNode.children)
  2496. if (itm !== nav)
  2497. hide(itm);
  2498. else break;
  2499. }
  2500.  
  2501. FixNavMenu: {
  2502. // hide ad link from the navigation
  2503. let ad = _document.querySelector('.menu-main-item > a > svg');
  2504. if (!ad) {
  2505. if (log) _console.warn('Unable to locate menu ad item');
  2506. break FixNavMenu;
  2507. } else {
  2508. ad = ad.parentNode.parentNode;
  2509. hide(ad);
  2510. }
  2511. }
  2512.  
  2513. SidebarAds: {
  2514. // remove ads from sidebar
  2515. let aside = _document.querySelectorAll('[class]:not([id]) > [id]:not([class]) > :first-child + :last-child:not(.v-panel)');
  2516. if (!aside.length) {
  2517. if (log) _console.warn('Unable to locate sidebar');
  2518. break SidebarAds;
  2519. }
  2520. let post;
  2521. for (let side of aside) {
  2522. if (log) _console.log('Processing potential sidebar:', side);
  2523. for (let itm of Array.from(side.children)) {
  2524. post = itm.classList.contains('post');
  2525. if (post) continue;
  2526. if (itm.querySelector('iframe') || !itm.children.length)
  2527. remove(itm);
  2528. let script = itm.querySelector('script');
  2529. if (itm.querySelector('a[target="_blank"] > img') ||
  2530. script && script.src === '' && (script.type === 'text/javascript' || !script.type) &&
  2531. script.textContent.includes('document'))
  2532. hide(itm);
  2533. }
  2534. }
  2535. }
  2536. }
  2537.  
  2538. const cln = setInterval(() => cleaner(false), 50);
  2539.  
  2540. // hide banner next to logo
  2541. if (isForum)
  2542. createStyle('div[class]:not([id]) tr[valign="top"] > td:last-child { display: none !important }');
  2543. // clean page
  2544. window.addEventListener(
  2545. 'DOMContentLoaded',
  2546. function () {
  2547. clearInterval(cln);
  2548. const width = () => win.innerWidth || _de.clientWidth || _document.body.clientWidth || 0,
  2549. height = () => win.innerHeight || _de.clientHeight || _document.body.clientHeight || 0;
  2550.  
  2551. if (isForum) {
  2552. // hide banner next to logo
  2553. //let itm = _document.querySelector('#logostrip');
  2554. //if (itm) hide(itm.parentNode.nextSibling);
  2555. // clear background in the download frame
  2556. if (location.pathname.startsWith('/forum/dl/')) {
  2557. let setBackground = node => _setAttribute(
  2558. node,
  2559. 'style', (_getAttribute(node, 'style') || '') +
  2560. ';background-color:#4ebaf6!important'
  2561. );
  2562. setBackground(_document.body);
  2563. for (let itm of _document.querySelectorAll('body > div'))
  2564. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer'))
  2565. remove(itm);
  2566. else
  2567. setBackground(itm);
  2568. }
  2569. // exist from DOMContentLoaded since the rest is not for forum
  2570. return;
  2571. }
  2572.  
  2573. cleaner(false);
  2574.  
  2575. _document.body.setAttribute('style', (_document.body.getAttribute('style') || '') + ';background-color:#E6E7E9!important');
  2576.  
  2577. let extra = 'background-image:none!important;background-color:transparent!important',
  2578. fakeStyles = new WeakMap(),
  2579. styleProxy = {
  2580. get(target, prop) {
  2581. return fakeStyles.get(target)[prop] || target[prop];
  2582. },
  2583. set(target, prop, value) {
  2584. let fakeStyle = fakeStyles.get(target);
  2585. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2586. return true;
  2587. }
  2588. };
  2589. for (let itm of _document.querySelectorAll('[id]:not(A), A')) {
  2590. if (!(itm.offsetWidth > 0.95 * width() &&
  2591. itm.offsetHeight > 0.85 * height()))
  2592. continue;
  2593. if (itm.tagName !== 'A') {
  2594. fakeStyles.set(itm.style, {
  2595. 'backgroundImage': itm.style.backgroundImage,
  2596. 'backgroundColor': itm.style.backgroundColor
  2597. });
  2598.  
  2599. try {
  2600. Object.defineProperty(itm, 'style', {
  2601. value: new Proxy(itm.style, styleProxy),
  2602. enumerable: true
  2603. });
  2604. } catch (e) {
  2605. _console.log('Unable to protect style property.', e);
  2606. }
  2607.  
  2608. _setAttribute(itm, 'style', `${(_getAttribute(itm, 'style') || '')};${extra}`);
  2609. }
  2610. if (itm.tagName === 'A')
  2611. _setAttribute(itm, 'style', 'display:none!important');
  2612. }
  2613. }
  2614. );
  2615. }
  2616. },
  2617.  
  2618. 'adhands.ru': () => scriptLander(() => {
  2619. try {
  2620. let _adv;
  2621. Object.defineProperty(win, 'adv', {
  2622. get() {
  2623. return _adv;
  2624. },
  2625. set(val) {
  2626. _console.log('Blocked advert on adhands.ru.');
  2627. nt.defineOn(val, 'advert', '', 'adv.');
  2628. _adv = val;
  2629. }
  2630. });
  2631. } catch (ignore) {
  2632. if (!win.adv)
  2633. _console.log('Unable to locate advert on adhands.ru.');
  2634. else {
  2635. _console.log('Blocked advert on adhands.ru.');
  2636. nt.define('adv.advert', '');
  2637. }
  2638. }
  2639. }, nullTools),
  2640.  
  2641. 'all-episodes.org': () => {
  2642. nt.define('perROS', 0); // blocks access when = 1
  2643. nt.define('idm', -1); // blocks quality when >= 0
  2644. nt.define('detdet', nt.func(null, 'detdet'));
  2645. // skip check for ads
  2646. win.setTimeout = new Proxy(win.setTimeout, {
  2647. apply(fun, that, args) {
  2648. if (args[0]) {
  2649. const text = _toString(args[0]);
  2650. if (text.includes('#bip') || text.includes('#advtss')) {
  2651. _console.log('Skipped check.');
  2652. return;
  2653. }
  2654. }
  2655. return _apply(fun, that, args);
  2656. }
  2657. });
  2658. // wrap player to prevent some events and interactions
  2659. let _playerInstance = win.playerInstance;
  2660. Object.defineProperty(win, 'playerInstance', {
  2661. get() {
  2662. return _playerInstance;
  2663. },
  2664. set(vl) {
  2665. _console.log('player', vl);
  2666. vl.on = new Proxy(vl.on, {
  2667. apply(fun, that, args) {
  2668. if (/^(ad[A-Z]|before(Play|Complete))/.test(args[0]))
  2669. return;
  2670. return _apply(fun, that, args);
  2671. }
  2672. });
  2673. vl.getAdBlock = () => false;
  2674. _playerInstance = vl;
  2675. }
  2676. });
  2677. },
  2678.  
  2679. 'allhentai.ru': () => {
  2680. preventPopups();
  2681. scriptLander(() => {
  2682. selectiveEval();
  2683. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2684. if (!_onerror)
  2685. return;
  2686. _onerror.set = (...args) => _console.log(args[0].toString());
  2687. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2688. }, selectiveEval);
  2689. },
  2690.  
  2691. 'allmovie.pro': {
  2692. other: 'rufilmtv.org',
  2693. dom() {
  2694. // pretend to be Android to make site use different played for ads
  2695. if (isSafari)
  2696. return;
  2697. Object.defineProperty(navigator, 'userAgent', {
  2698. get() {
  2699. 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';
  2700. },
  2701. enumerable: true
  2702. });
  2703. }
  2704. },
  2705.  
  2706. 'ati.su': () => scriptLander(() => {
  2707. nt.define('Object.prototype.advManager', nt.proxy({}, 'advManager'));
  2708. }),
  2709.  
  2710. 'audioportal.su': {
  2711. now() {
  2712. createStyle('#blink2 { display: none !important }');
  2713. },
  2714. dom() {
  2715. let links = _document.querySelectorAll('a[onclick*="clickme("]');
  2716. if (!links) return;
  2717. for (let link of links)
  2718. win.clickme(link);
  2719. }
  2720. },
  2721.  
  2722. 'auto.ru': () => {
  2723. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  2724. let userAdsListAds = (
  2725. '.listing-list > .listing-item,' +
  2726. '.listing-item_type_fixed.listing-item'
  2727. );
  2728. let catalogAds = (
  2729. 'div[class*="layout_catalog-inline"],' +
  2730. 'div[class$="layout_horizontal"]'
  2731. );
  2732. let otherAds = (
  2733. '.advt_auto,' +
  2734. '.sidebar-block,' +
  2735. '.pager-listing + div[class],' +
  2736. '.card > div[class][style],' +
  2737. '.sidebar > div[class],' +
  2738. '.main-page__section + div[class],' +
  2739. '.listing > tbody'
  2740. );
  2741. gardener(userAdsListAds, words, {
  2742. root: '.listing-wrap',
  2743. observe: true
  2744. });
  2745. gardener(catalogAds, words, {
  2746. root: '.catalog__page,.content__wrapper',
  2747. observe: true
  2748. });
  2749. gardener(otherAds, words);
  2750. },
  2751.  
  2752. 'avito.ru': () => scriptLander(() => selectiveCookies('abp|cmtchd|crookie|is_adblock'), selectiveCookies),
  2753.  
  2754. 'di.fm': () => scriptLander(() => {
  2755. let log = false;
  2756. // wrap global app object to catch registration of specific modules
  2757. let _di = win.di;
  2758. Object.defineProperty(win, 'di', {
  2759. get() {
  2760. return _di;
  2761. },
  2762. set(vl) {
  2763. if (vl === _di)
  2764. return;
  2765. if (log) _console.trace('di =', vl);
  2766. _di = new Proxy(vl, {
  2767. set(di, name, vl) {
  2768. if (vl === di[name])
  2769. return true;
  2770. if (name === 'app') {
  2771. if (log) _console.trace(`di.${name} =`, vl);
  2772. if (!('module' in vl))
  2773. return;
  2774. vl.module = new Proxy(vl.module, {
  2775. apply(module, that, args) {
  2776. if (/Wall|Banner|Detect|WebplayerApp\.Ads/.test(args[0])) {
  2777. let name = args[0];
  2778. if (log) _console.log('wrap', name, 'module');
  2779. if (typeof args[1] === 'function')
  2780. args[1] = new Proxy(args[1], {
  2781. apply(fun, that, args) {
  2782. if (args[0]) // module object
  2783. args[0].start = () => _console.log('Skipped start of', name);
  2784. return Reflect.apply(fun, that, args);
  2785. }
  2786. });
  2787. } // else log && _console.log('loading module', args[0]);
  2788. if (args[0] === 'Modals' && typeof args[1] === 'function') {
  2789. if (log) _console.log('wrap', name, 'module');
  2790. args[1] = new Proxy(args[1], {
  2791. apply(fun, that, args) {
  2792. if ('commands' in args[1] && 'setHandlers' in args[1].commands &&
  2793. !Object.hasOwnProperty.call(args[1].commands, 'setHandlers')) {
  2794. let _commands = args[1].commands;
  2795. _commands.setHandlers = new Proxy(_commands.setHandlers, {
  2796. apply(fun, that, args) {
  2797. const noopFunc = name => () => _console.log('Skipped', name, 'window');
  2798. for (let name in args[0])
  2799. if (name === 'modal:streaminterrupt' ||
  2800. name === 'modal:midroll')
  2801. args[0][name] = noopFunc(name);
  2802. delete _commands.setHandlers;
  2803. return Reflect.apply(fun, that, args);
  2804. }
  2805. });
  2806. }
  2807. return Reflect.apply(fun, that, args);
  2808. }
  2809. });
  2810. }
  2811. return Reflect.apply(module, that, args);
  2812. }
  2813. });
  2814. }
  2815. di[name] = vl;
  2816. }
  2817. });
  2818. }
  2819. });
  2820. // don't send errorception logs
  2821. Object.defineProperty(win, 'onerror', {
  2822. set(vl) {
  2823. if (log) _console.trace('Skipped global onerror callback:', vl);
  2824. }
  2825. });
  2826. }),
  2827.  
  2828. 'draug.ru': {
  2829. other: 'vargr.ru',
  2830. now: () => scriptLander(() => {
  2831. if (location.pathname === '/pop.html')
  2832. win.close();
  2833. createStyle({
  2834. '#timer_1': {
  2835. display: 'none !important'
  2836. },
  2837. '#timer_2': {
  2838. display: 'block !important'
  2839. }
  2840. });
  2841. let _contentWindow = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow');
  2842. let _get_contentWindow = _bindCall(_contentWindow.get);
  2843. _contentWindow.get = function () {
  2844. let res = _get_contentWindow(this);
  2845. if (res.location.href === 'about:blank')
  2846. res.document.write = (...args) => _console.log('Skipped iframe.write(', ...args, ')');
  2847. return res;
  2848. };
  2849. Object.defineProperty(HTMLIFrameElement.prototype, 'contentWindow', _contentWindow);
  2850. }),
  2851. dom() {
  2852. let list = _querySelectorAll('div[id^="yandex_rtb_"], .adsbygoogle');
  2853. list.forEach(node => _console.log('Removed:', node.parentNode.parentNode.removeChild(node.parentNode)));
  2854. }
  2855. },
  2856.  
  2857. 'drive2.ru': () => {
  2858. gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2859. scriptLander(() => {
  2860. selectiveCookies();
  2861. let _d2;
  2862. Object.defineProperty(win, 'd2', {
  2863. get() {
  2864. return _d2;
  2865. },
  2866. set(vl) {
  2867. if (vl === _d2)
  2868. return true;
  2869. _d2 = new Proxy(vl, {
  2870. set(target, prop, val) {
  2871. if (['brandingRender', 'dvReveal', '__dv'].includes(prop))
  2872. val = () => null;
  2873. target[prop] = val;
  2874. return true;
  2875. }
  2876. });
  2877. }
  2878. });
  2879. // obfuscated Yandex.Direct
  2880. nt.define('Object.prototype.initYaDirect', undefined);
  2881. }, nullTools, selectiveCookies);
  2882. },
  2883.  
  2884. 'echo.msk.ru': () => scriptLander(() => {
  2885. selectiveCookies();
  2886. selectiveEval(evalPatternYandex, /^document\.write/, /callAdblock/);
  2887. }, selectiveEval, selectiveCookies),
  2888.  
  2889. 'eurogamer.tld': {
  2890. other: 'metabomb.net, usgamer.net',
  2891. now: () => scriptLander(() => {
  2892. abortExecution.inlineScript('_sp_');
  2893. selectiveCookies('sp');
  2894. }, selectiveCookies, abortExecution)
  2895. },
  2896.  
  2897. 'fastpic.ru': () => {
  2898. // Had to obfuscate property name to avoid triggering anti-obfuscation on greasyfork.org -_- (Exception 403012)
  2899. nt.define(`_0x${'4955'}`, []);
  2900. },
  2901.  
  2902. 'fishki.net': () => {
  2903. scriptLander(() => {
  2904. const fishki = {};
  2905. const adv = nt.proxy({
  2906. afterAdblockCheck: nt.func(null, 'fishki.afterAdblockCheck'),
  2907. refreshFloat: nt.func(null, 'fishki.refreshFloat')
  2908. });
  2909. nt.defineOn(fishki, 'adv', adv, 'fishki.');
  2910. nt.defineOn(fishki, 'is_adblock', false, 'fishki.');
  2911. nt.define('fishki', fishki);
  2912. nt.define('Object.prototype.detect', nt.func(undefined, 'detect'));
  2913. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  2914. apply(fun, that, args) {
  2915. if (['is_adblock', 'adv'].includes(args[1]) || args[0] === adv)
  2916. return;
  2917. return _apply(fun, that, args);
  2918. }
  2919. });
  2920. }, nullTools);
  2921. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2922. },
  2923.  
  2924. 'forbes.com': () => {
  2925. createStyle(['fbs-ad[ad-id], .top-ad-container, .fbs-ad-wrapper, .footer-ad-labeling, .ad-rail, .ad-unit { display: none !important; }']);
  2926. nt.define('Object.prototype.isAdLight', true);
  2927. nt.define('Object.prototype.initializeAd', nt.func(undefined, '?.initializeAd'));
  2928. win.getComputedStyle = new Proxy(win.getComputedStyle, {
  2929. apply(fun, that, args) {
  2930. let res = _apply(fun, that, args);
  2931. if (res.display === 'none')
  2932. nt.defineOn(res, 'display', 'block', 'getComputedStyle().');
  2933. if (res.visibility === 'hidden')
  2934. nt.defineOn(res, 'visibility', 'visible', 'getComputedStyle().');
  2935. return res;
  2936. }
  2937. });
  2938. win.CSSStyleDeclaration.prototype.getPropertyValue = new Proxy(win.CSSStyleDeclaration.prototype.getPropertyValue, {
  2939. apply(fun, that, args) {
  2940. let res = _apply(fun, that, args);
  2941. if (args[0] === 'display' && res === 'none')
  2942. return 'block';
  2943. if (args[0] === 'visibility' && res === 'hidden')
  2944. return 'visible';
  2945. return res;
  2946. }
  2947. });
  2948. },
  2949.  
  2950. 'friends.in.ua': () => scriptLander(() => {
  2951. Object.defineProperty(win, 'need_warning', {
  2952. get() {
  2953. return 0;
  2954. },
  2955. set() {}
  2956. });
  2957. }),
  2958.  
  2959. 'gamerevolution.com': () => {
  2960. const _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight');
  2961. _clientHeight.get = new Proxy(_clientHeight.get, {
  2962. apply(...args) {
  2963. return _apply(...args) || 1;
  2964. }
  2965. });
  2966. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  2967.  
  2968. const toReplace = [
  2969. 'blockerDetected', 'disableDetected', 'hasAdBlocker',
  2970. 'hasBlockerFlag', 'hasDisabledAdBlocker', 'hasBlocker'
  2971. ];
  2972. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  2973. apply(fun, that, args) {
  2974. if (toReplace.includes(args[1])) {
  2975. args[2] = {
  2976. value() {
  2977. return false;
  2978. }
  2979. };
  2980. console.log(args);
  2981. }
  2982. return _apply(fun, that, args);
  2983. }
  2984. });
  2985. },
  2986.  
  2987. 'gamersheroes.com': () => abortExecution.inlineScript('document.createElement', {
  2988. pattern: /window\[\w+\(\[(\d+,?\s?)+\],\s?\w+\)\]/
  2989. }),
  2990.  
  2991. 'gidonline.club': () => createStyle('.tray > div[style] {display: none!important}'),
  2992.  
  2993. 'glav.su': () => scriptLander(() => {
  2994. abortExecution.inlineScript('EventTarget.prototype.addEventListener', {
  2995. pattern: /nosferatu/
  2996. });
  2997. }, abortExecution),
  2998.  
  2999. 'gorodrabot.ru': () => scriptLander(() => {
  3000. abortExecution.onGet('Object.prototype.yaads');
  3001. abortExecution.onGet('Object.prototype.initYaDirect');
  3002. }, abortExecution),
  3003.  
  3004. 'hdgo.cc': {
  3005. other: '46.30.43.38, couber.be',
  3006. now() {
  3007. (new MutationObserver(
  3008. ms => {
  3009. let m, node;
  3010. for (m of ms)
  3011. for (node of m.addedNodes)
  3012. if (node.tagName instanceof HTMLScriptElement && _getAttribute(node, 'onerror') !== null)
  3013. node.removeAttribute('onerror');
  3014. }
  3015. )).observe(_document.documentElement, {
  3016. childList: true,
  3017. subtree: true
  3018. });
  3019. }
  3020. },
  3021.  
  3022. 'gamepur.com': () => {
  3023. nt.define('ga', nt.func(null, 'ga'));
  3024. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  3025. apply(fun, that, args) {
  3026. if (typeof args[1] === 'string' &&
  3027. (args[1] === 'hasAdblocker' || args[1] === 'blockerDetected'))
  3028. throw new ReferenceError(`${args[1]} is not defined`);
  3029. return Reflect.apply(fun, that, args);
  3030. }
  3031. });
  3032. },
  3033.  
  3034. 'gismeteo.tld': {
  3035. now: () => scriptLander(() => {
  3036. gardener('div > script', /AdvManager/i, {
  3037. observe: true,
  3038. parent: 'div'
  3039. });
  3040. }, nullTools, selectiveCookies)
  3041. },
  3042.  
  3043. 'hdrezka.ag': () => {
  3044. Object.defineProperty(win, 'ab', {
  3045. value: false,
  3046. enumerable: true
  3047. });
  3048. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  3049. },
  3050.  
  3051. 'hqq.tv': () => scriptLander(() => {
  3052. // disable anti-debugging in hqq.tv player
  3053. 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);
  3054. deepWrapAPI(root => {
  3055. // skip obfuscated stuff and a few other calls
  3056. let _setInterval = root.setInterval,
  3057. _setTimeout = root.setTimeout;
  3058. root.setInterval = (...args) => {
  3059. let fun = args[0];
  3060. if (typeof fun === 'function') {
  3061. let text = _toString(fun),
  3062. skip = text.includes('check();') || isObfuscated(text);
  3063. _console.trace('setInterval', text, 'skip', skip);
  3064. if (skip) return -1;
  3065. }
  3066. return _setInterval.apply(this, args);
  3067. };
  3068. let wrappedST = new WeakSet();
  3069. root.setTimeout = (...args) => {
  3070. let fun = args[0];
  3071. if (typeof fun === 'function') {
  3072. let text = _toString(fun),
  3073. skip = fun.name === 'check' || isObfuscated(text);
  3074. if (!wrappedST.has(fun)) {
  3075. _console.trace('setTimeout', text, 'skip', skip);
  3076. wrappedST.add(fun);
  3077. }
  3078. if (skip) return;
  3079. }
  3080. return _setTimeout.apply(this, args);
  3081. };
  3082. // skip 'debugger' call
  3083. let _eval = root.eval;
  3084. root.eval = text => {
  3085. if (typeof text === 'string' && text.includes('debugger;')) {
  3086. _console.trace('skip eval', text);
  3087. return;
  3088. }
  3089. _eval(text);
  3090. };
  3091. // Prevent RegExpt + toString trick
  3092. let _proto;
  3093. try {
  3094. _proto = root.RegExp.prototype;
  3095. } catch (ignore) {
  3096. return;
  3097. }
  3098. let _RE_tS = Object.getOwnPropertyDescriptor(_proto, 'toString');
  3099. let _RE_tSV = _RE_tS.value || _RE_tS.get();
  3100. Object.defineProperty(_proto, 'toString', {
  3101. enumerable: _RE_tS.enumerable,
  3102. configurable: _RE_tS.configurable,
  3103. get() {
  3104. return _RE_tSV;
  3105. },
  3106. set(val) {
  3107. _console.trace('Attempt to change toString for', this, 'with', _toString(val));
  3108. }
  3109. });
  3110. });
  3111. }, deepWrapAPI),
  3112.  
  3113. 'hideip.me': {
  3114. now: () => scriptLander(() => {
  3115. let _innerHTML = Object.getOwnPropertyDescriptor(_Element, 'innerHTML');
  3116. let _set_innerHTML = _innerHTML.set;
  3117. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  3118. let _get_innerText = _innerText.get;
  3119. let div = _document.createElement('div');
  3120. _innerHTML.set = function (...args) {
  3121. _set_innerHTML.call(div, args[0].replace('i', 'a'));
  3122. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div)) ||
  3123. /(\d\d\d?\.){3}\d\d\d?:\d/.test(_get_innerText.call(this))) {
  3124. _console.log('Anti-Adblock killed.');
  3125. return true;
  3126. }
  3127. _set_innerHTML.apply(this, args);
  3128. };
  3129. Object.defineProperty(_Element, 'innerHTML', _innerHTML);
  3130. Object.defineProperty(win, 'adblock', {
  3131. get() {
  3132. return false;
  3133. },
  3134. set() {},
  3135. enumerable: true
  3136. });
  3137. let _$ = {};
  3138. let _$_map = new WeakMap();
  3139. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  3140. let _val_gOPD = _gOPD.value;
  3141. _gOPD.value = function (...args) {
  3142. let _res = _val_gOPD.apply(this, args);
  3143. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  3144. delete _res.get;
  3145. delete _res.set;
  3146. _res.value = win[args[1]];
  3147. }
  3148. return _res;
  3149. };
  3150. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  3151. let getJQWrap = (n) => {
  3152. let name = n;
  3153. return {
  3154. enumerable: true,
  3155. get() {
  3156. return _$[name];
  3157. },
  3158. set(x) {
  3159. if (_$_map.has(x)) {
  3160. _$[name] = _$_map.get(x);
  3161. return true;
  3162. }
  3163. if (x === _$.$ || x === _$.jQuery) {
  3164. _$[name] = x;
  3165. return true;
  3166. }
  3167. _$[name] = new Proxy(x, {
  3168. apply(t, o, args) {
  3169. let _res = t.apply(o, args);
  3170. if (_$_map.has(_res.is))
  3171. _res.is = _$_map.get(_res.is);
  3172. else {
  3173. let _is = _res.is;
  3174. _res.is = function (...args) {
  3175. if (args[0] === ':hidden')
  3176. return false;
  3177. return _is.apply(this, args);
  3178. };
  3179. _$_map.set(_is, _res.is);
  3180. }
  3181. return _res;
  3182. }
  3183. });
  3184. _$_map.set(x, _$[name]);
  3185. return true;
  3186. }
  3187. };
  3188. };
  3189. Object.defineProperty(win, '$', getJQWrap('$'));
  3190. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  3191. let _dP = Object.defineProperty;
  3192. Object.defineProperty = function (...args) {
  3193. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  3194. return undefined;
  3195. return _dP.apply(this, args);
  3196. };
  3197. })
  3198. },
  3199.  
  3200. 'igra-prestoloff.cx': () => scriptLander(() => {
  3201. /*jslint evil: true */ // yes, evil, I know
  3202. let _write = _document.write.bind(_document);
  3203. /*jslint evil: false */
  3204. nt.define('document.write', t => {
  3205. let id = t.match(/jwplayer\("(\w+)"\)/i);
  3206. if (id && id[1])
  3207. return _write(`<div id="${id[1]}"></div>${t}`);
  3208. return _write('');
  3209. }, {
  3210. enumerable: true
  3211. });
  3212. }),
  3213.  
  3214. 'imageban.ru': () => {
  3215. Object.defineProperty(win, 'V7x1J', {
  3216. get() {
  3217. return null;
  3218. }
  3219. });
  3220. },
  3221.  
  3222. 'inoreader.com': () => scriptLander(() => {
  3223. let i = setInterval(() => {
  3224. if ('adb_detected' in win) {
  3225. win.adb_detected = () => win.adb_not_detected();
  3226. clearInterval(i);
  3227. }
  3228. }, 10);
  3229. _document.addEventListener('DOMContentLoaded', () => clearInterval(i), false);
  3230. }),
  3231.  
  3232. 'it-actual.ru': () => scriptLander(() => {
  3233. abortExecution.onAll('blocked');
  3234. abortExecution.onGet('nsg');
  3235. }, abortExecution),
  3236.  
  3237. 'ivi.ru': () => {
  3238. let _xhr_open = win.XMLHttpRequest.prototype.open;
  3239. win.XMLHttpRequest.prototype.open = function (method, url, ...args) {
  3240. if (typeof url === 'string')
  3241. if (url.endsWith('/track'))
  3242. return;
  3243. return _xhr_open.call(this, method, url, ...args);
  3244. };
  3245. let _responseText = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype, 'responseText');
  3246. let _responseText_get = _responseText.get;
  3247. _responseText.get = function () {
  3248. if (this.__responseText__)
  3249. return this.__responseText__;
  3250. let res = _responseText_get.apply(this, arguments);
  3251. let o;
  3252. try {
  3253. if (res)
  3254. o = JSON.parse(res);
  3255. } catch (ignore) {}
  3256. let changed = false;
  3257. if (o && o.result) {
  3258. if (o.result instanceof Array &&
  3259. 'adv_network_logo_url' in o.result[0]) {
  3260. o.result = [];
  3261. changed = true;
  3262. }
  3263. if (o.result.show_adv) {
  3264. o.result.show_adv = false;
  3265. changed = true;
  3266. }
  3267. }
  3268. if (changed) {
  3269. _console.log('changed response >>', o);
  3270. res = JSON.stringify(o);
  3271. }
  3272. this.__responseText__ = res;
  3273. return res;
  3274. };
  3275. Object.defineProperty(XMLHttpRequest.prototype, 'responseText', _responseText);
  3276. },
  3277.  
  3278. 'kakprosto.ru': () => scriptLander(() => {
  3279. selectiveCookies('yadb');
  3280. abortExecution.inlineScript('yaProxy', {
  3281. pattern: /yadb/
  3282. });
  3283. abortExecution.inlineScript('yandexContextAsyncCallbacks');
  3284. abortExecution.inlineScript('adfoxAsyncParams');
  3285. abortExecution.inlineScript('adfoxBackGroundLoaded');
  3286. }, selectiveCookies, abortExecution),
  3287.  
  3288. 'kinopoisk.ru': () => {
  3289. // filter cookies
  3290. // set no-branding body style and adjust other blocks on the page
  3291. const style = {
  3292. '.app__header.app__header_margin-bottom_brand, #top': {
  3293. margin_bottom: '20px !important'
  3294. },
  3295. '.app__branding': {
  3296. display: 'none!important'
  3297. }
  3298. };
  3299. if (location.hostname === 'www.kinopoisk.ru' && !location.pathname.startsWith('/games/'))
  3300. style['html:not(#id), body:not(#id), .app-container'] = {
  3301. background: '#d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important'
  3302. };
  3303. createStyle(style);
  3304. scriptLander(() => {
  3305. selectiveCookies('cmtchd|crookie|kpunk');
  3306. // filter JSON
  3307. win.JSON.parse = new Proxy(win.JSON.parse, {
  3308. apply(fun, that, args) {
  3309. let o = _apply(fun, that, args);
  3310. let name = 'antiAdBlockCookieName';
  3311. if (name in o && typeof o[name] === 'string')
  3312. selectiveCookies(o[name]);
  3313. name = 'branding';
  3314. if (name in o) o[name] = {};
  3315. // tricks against ads in the trailer player
  3316. // if (location.hostname.startsWith('widgets.'))
  3317. if (o.page && o.page.playerParams)
  3318. delete o.page.playerParams.adConfig;
  3319. if (o.common && o.common.bunker && o.common.bunker.adv && o.common.bunker.adv.filmIdWithoutAd)
  3320. o.common.bunker.adv.filmIdWithoutAd.includes = () => true;
  3321. //_console.log('JSON.parse', o);
  3322. return o;
  3323. }
  3324. });
  3325. // skip timeout check for blocked requests
  3326. win.setTimeout = new Proxy(win.setTimeout, {
  3327. apply(fun, that, args) {
  3328. if (args[1] === 100) {
  3329. let str = _toString(args[0]);
  3330. if (str.endsWith('{a()}') || str.endsWith('{n()}'))
  3331. return;
  3332. }
  3333. return _apply(fun, that, args);
  3334. }
  3335. });
  3336. // obfuscated Yandex.Direct
  3337. nt.define('Object.prototype.initYaDirect', undefined);
  3338. nt.define('Object.prototype._resolveDetectResult', () => null);
  3339. nt.define('Object.prototype.detectResultPromise', new Promise(r => r(false)));
  3340. if (location.hostname === 'www.kinopoisk.ru')
  3341. nt.define('Object.prototype.initAd', nt.func(undefined, 'initAd'));
  3342. // catch branding and other things
  3343. let _KP;
  3344. Object.defineProperty(win, 'KP', {
  3345. get() {
  3346. return _KP;
  3347. },
  3348. set(val) {
  3349. if (_KP === val)
  3350. return true;
  3351. _KP = new Proxy(val, {
  3352. set(kp, name, val) {
  3353. if (name === 'branding') {
  3354. kp[name] = new Proxy({
  3355. weborama: {}
  3356. }, {
  3357. get(kp, name) {
  3358. return name in kp ? kp[name] : '';
  3359. },
  3360. set() {}
  3361. });
  3362. return true;
  3363. }
  3364. if (name === 'config')
  3365. val = new Proxy(val, {
  3366. set(cfg, name, val) {
  3367. if (name === 'anContextUrl')
  3368. return true;
  3369. if (name === 'adfoxEnabled' || name === 'hasBranding')
  3370. val = false;
  3371. if (name === 'adfoxVideoAdUrls')
  3372. val = {
  3373. flash: {},
  3374. html: {}
  3375. };
  3376. cfg[name] = val;
  3377. return true;
  3378. }
  3379. });
  3380. kp[name] = val;
  3381. return true;
  3382. }
  3383. });
  3384. _console.log('KP =', val);
  3385. }
  3386. });
  3387. }, selectiveCookies, nullTools);
  3388. },
  3389.  
  3390. 'korrespondent.net': {
  3391. now: () => scriptLander(() => {
  3392. nt.define('holder', function (id) {
  3393. let div = _document.getElementById(id);
  3394. if (!div)
  3395. return;
  3396. if (div.parentNode.classList.contains('col__sidebar')) {
  3397. div.parentNode.appendChild(div);
  3398. div.style.height = '300px';
  3399. }
  3400. });
  3401. }, nullTools),
  3402. dom() {
  3403. for (let frame of _document.querySelectorAll('.unit-side-informer > iframe'))
  3404. frame.parentNode.style.width = '1px';
  3405. }
  3406. },
  3407.  
  3408. 'libertycity.ru': () => scriptLander(() => {
  3409. nt.define('adBlockEnabled', false);
  3410. }, nullTools),
  3411.  
  3412. 'liveinternet.ru': () => scriptLander(() => {
  3413. abortExecution.onGet('Object.prototype.initAd');
  3414. }, abortExecution),
  3415.  
  3416. 'livejournal.com': () => scriptLander(() => {
  3417. nt.define('Object.prototype.Adf', undefined);
  3418. nt.define('Object.prototype.Begun', undefined);
  3419. }, nullTools),
  3420.  
  3421. 'mail.ru': {
  3422. other: 'ok.ru, sportmail.ru',
  3423. now: () => scriptLander(() => {
  3424. const _hostparts = location.hostname.split('.');
  3425. const _subdomain = _hostparts.slice(-3).join('.');
  3426. const _hostname = _hostparts.slice(-2).join('.');
  3427. const _emailru = _subdomain === 'e.mail.ru' || _subdomain === 'octavius.mail.ru';
  3428. const _mymailru = _subdomain === 'my.mail.ru';
  3429. const _okru = _hostname === 'ok.ru';
  3430. // setTimeout filter
  3431. // advBlock|rbParams - ads
  3432. // document\.title= - blinking title on background news load on main page
  3433. const pattern = /advBlock|rbParams|document\.title=/i;
  3434. const _setTimeout = win.setTimeout;
  3435. win.setTimeout = function setTimeout(...args) {
  3436. let text = _toString(args[0]);
  3437. if (pattern.test(text)) {
  3438. _console.trace('Skipped setTimeout:', text);
  3439. return;
  3440. }
  3441. return _setTimeout(...args);
  3442. };
  3443.  
  3444. // Trick to prevent mail.ru from removing 3rd-party styles
  3445. nt.define('Object.prototype.restoreVisibility', nt.func(null, 'restoreVisibility'));
  3446. // Other Yandex Direct and other ads
  3447. nt.define('Object.prototype.initMimic', undefined);
  3448. nt.define('Object.prototype.hpConfig', undefined);
  3449. nt.define('Object.prototype.direct', undefined);
  3450. const getAds = () => new Promise(
  3451. r => r(nt.proxy({}, '?.getAds()'))
  3452. );
  3453. nt.define('Object.prototype.getAds', getAds);
  3454. nt.define('rb_counter', nt.func(null, 'rb_counter'));
  3455. if (_subdomain === 'mail.ru') { // main page
  3456. nt.define('Object.prototype.baits', undefined); // detector
  3457. nt.define('Object.prototype.getFeed', nt.func(null, 'pulse.getFeed')); // Pulse feed
  3458. createStyle('body > div > .pulse { display: none !important }');
  3459. }
  3460. if (_emailru)
  3461. nt.define('Object.prototype.show_me_ads', undefined);
  3462. else if (_mymailru)
  3463. nt.define('Object.prototype.runMimic', nt.func(null, 'runMimic'));
  3464. else {
  3465. nt.define('Object.prototype.mimic', undefined);
  3466. const xray = nt.func(undefined, 'xray');
  3467. nt.defineOn(xray, 'send', nt.func(undefined, 'xray.send'), 'xray.');
  3468. nt.defineOn(xray, 'radarPrefix', null, 'xray.');
  3469. nt.defineOn(xray, 'xrayRadarUrl', undefined, 'xray.');
  3470. nt.defineOn(xray, 'defaultParams', nt.proxy({
  3471. i: undefined,
  3472. p: 'media'
  3473. }), 'xray.');
  3474. nt.define('Object.prototype.xray', nt.proxy(xray));
  3475. }
  3476. // shenanigans against ok.ru ABP detector
  3477. if (_okru) {
  3478. abortExecution.onGet('OK.hooks');
  3479. // banners on ok.ru and counter
  3480. nt.define('getAdvTargetParam', nt.func(null, 'getAdvTargetParam'));
  3481. // break detection in case detector wasn't wrapped
  3482. abortExecution.onSet('Object.prototype.adBlockDetected');
  3483. }
  3484. // news.mail.ru and sportmail.ru
  3485. abortExecution.onGet('myWidget');
  3486. // cleanup e.mail.ru configs and mimic config on news and sport
  3487. const emptyString = (root, name) => root[name] && (root[name] = '');
  3488. const detectMimic = /direct|240x400|SlotView/;
  3489. win.JSON.parse = new Proxy(win.JSON.parse, {
  3490. apply(fun, that, args) {
  3491. let o = _apply(fun, that, args);
  3492. if (o && typeof o === 'object') {
  3493. if (o.cfg && o.cfg.sotaFeatures) {
  3494. let root = o.cfg.sotaFeatures;
  3495. if (Array.isArray(root.adv)) root.adv = [];
  3496. for (let name in root)
  3497. if (name.startsWith('adv-') || name.startsWith('adman-'))
  3498. delete root[name];
  3499. ['email_logs_to', 'smokescreen-locators'].forEach(name => emptyString(root, name));
  3500. }
  3501. if (o.userConfig) {
  3502. if (Array.isArray(o.userConfig.honeypot))
  3503. o.userConfig.honeypot.forEach((v, id, me) => (me[id] = []));
  3504. const cfg = o.userConfig.config;
  3505. if (cfg && cfg.honeypot)
  3506. emptyString(cfg.honeypot, 'baits');
  3507. }
  3508. if (o.body) {
  3509. const flags = o.body.common_purpose_flags;
  3510. if (flags && 'hide_ad_in_mail_web' in flags)
  3511. flags.hide_ad_in_mail_web = true;
  3512. if (o.body.show_me_ads)
  3513. o.body.show_me_ads = false;
  3514. }
  3515. //_console.log('JSON.parse', o);
  3516. }
  3517. if (Array.isArray(o))
  3518. if (o.some(t => typeof t === 'string' && detectMimic.test(t))) {
  3519. _console.log('Replaced', o);
  3520. o = [];
  3521. } //else _console.log('JSON.parse', o);
  3522. return o;
  3523. }
  3524. });
  3525. // all the rest is only needed on main page and in emails
  3526. if (_subdomain !== 'mail.ru' && !_emailru && !_okru)
  3527. return;
  3528.  
  3529. // Disable page scrambler on mail.ru to let extensions easily block ads there
  3530. let logger = {
  3531. apply(fun, that, args) {
  3532. let res = _apply(fun, that, args);
  3533. _console.log(`${fun._name}(`, ...args, `)\n>>`, res);
  3534. return res;
  3535. }
  3536. };
  3537.  
  3538. function wrapLocator(locator) {
  3539. if ('setup' in locator) {
  3540. let _setup = locator.setup;
  3541. locator.setup = function (o) {
  3542. if ('enable' in o) {
  3543. o.enable = false;
  3544. _console.log('Disable mimic mode.');
  3545. }
  3546. if ('links' in o) {
  3547. o.links = [];
  3548. _console.log('Call with empty list of sheets.');
  3549. }
  3550. return _setup.call(this, o);
  3551. };
  3552. locator.insertSheet = () => false;
  3553. locator.wrap = () => false;
  3554. }
  3555. try {
  3556. let names = [];
  3557. for (let name in locator)
  3558. if (typeof locator[name] === 'function' && name !== 'transform') {
  3559. locator[name]._name = "locator." + name;
  3560. locator[name] = new Proxy(locator[name], logger);
  3561. names.push(name);
  3562. }
  3563. _console.log(`[locator] wrapped properties: ${names.length ? names.join(', ') : '[empty]'}`);
  3564. } catch (e) {
  3565. _console.log(e);
  3566. }
  3567. return locator;
  3568. }
  3569.  
  3570. function defineLocator(root) {
  3571. let _locator = root.locator;
  3572. let wrapLocatorSetter = vl => _locator = wrapLocator(vl);
  3573. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  3574. if (!loc_desc || loc_desc.set !== wrapLocatorSetter)
  3575. try {
  3576. Object.defineProperty(root, 'locator', {
  3577. set: wrapLocatorSetter,
  3578. get() {
  3579. return _locator;
  3580. }
  3581. });
  3582. } catch (err) {
  3583. _console.log('Unable to redefine "locator" object!!!', err);
  3584. }
  3585. if (loc_desc.value)
  3586. _locator = wrapLocator(loc_desc.value);
  3587. }
  3588.  
  3589. { // auto-stubs for various ad, detection and obfuscation modules
  3590. const missingCheck = {
  3591. get(obj, name) {
  3592. let res = obj[name];
  3593. if (!(name in obj))
  3594. _console.trace(`Missing "${name}" in`, obj);
  3595. return res;
  3596. }
  3597. };
  3598. const skipLog = (name, ret) => (...args) => (_console.log(`${name}(`, ...args, ')'), ret);
  3599. const createSkipAllObject = (baseName, obj = {
  3600. __esModule: true
  3601. }) => new Proxy(obj, {
  3602. get(obj, name) {
  3603. if (name in obj)
  3604. return obj[name];
  3605. _console.log(`Created stub for "${name}" in ${baseName}.`);
  3606. obj[name] = skipLog(`${baseName}.${name}`);
  3607. return obj[name];
  3608. },
  3609. set() {}
  3610. });
  3611. const redefiner = {
  3612. apply(fun, that, args) {
  3613. let res;
  3614. let warn = false;
  3615. let name = fun._name;
  3616. if (name === 'mrg-smokescreen/Welter')
  3617. res = {
  3618. isWelter() {
  3619. return true;
  3620. },
  3621. wrap: skipLog(`${name}.wrap`)
  3622. };
  3623. if (name === 'mrg-smokescreen/Honeypot')
  3624. res = {
  3625. check(...args) {
  3626. _console.log(`${name}.check(`, ...args, ')');
  3627. return new Promise(() => undefined);
  3628. },
  3629. version: "-1"
  3630. };
  3631. if (name === 'advert/adman/adman') {
  3632. let features = {
  3633. siteZones: {},
  3634. slots: {}
  3635. };
  3636. [
  3637. 'expId', 'siteId', 'mimicEndpoint', 'mimicPartnerId',
  3638. 'immediateFetchTimeout', 'delayedFetchTimeout'
  3639. ].forEach(name => void(features[name] = null));
  3640. res = createSkipAllObject(name, {
  3641. getFeatures: skipLog(`${name}.getFeatures`, features)
  3642. });
  3643. }
  3644. if (name === 'mrg-smokescreen/Utils')
  3645. res = createSkipAllObject(name, {
  3646. extend(...args) {
  3647. let res = {
  3648. enable: false,
  3649. match: [],
  3650. links: []
  3651. };
  3652. _console.log(`${name}.extend(`, ...args, ') >>', res);
  3653. return res;
  3654. }
  3655. });
  3656. if (name.startsWith('OK/banners/') ||
  3657. name.startsWith('mrg-smokescreen/StyleSheets') ||
  3658. name === '@mail/mimic' ||
  3659. name === 'mediator/advert-managers')
  3660. res = createSkipAllObject(name);
  3661. if (res) {
  3662. Object.defineProperty(res, Symbol.toStringTag, {
  3663. get() {
  3664. return `Skiplog object for ${name}`;
  3665. }
  3666. });
  3667. Object.defineProperty(res, Symbol.toPrimitive, {
  3668. value(hint) {
  3669. if (hint === 'string')
  3670. return Object.prototype.toString.call(this);
  3671. return `[missing toPrimitive] ${name} ${hint}`;
  3672. }
  3673. });
  3674. res = new Proxy(res, missingCheck);
  3675. } else {
  3676. res = _apply(fun, that, args);
  3677. warn = true;
  3678. }
  3679. _console[warn ? 'warn' : 'log'](name, '(', ...args, ')\n>>', res);
  3680. return res;
  3681. }
  3682. };
  3683.  
  3684. const advModuleNamesStartWith = /^(mrg-(context|honeypot)|adv\/)/;
  3685. const advModuleNamesGeneric = /advert|banner|mimic|smoke/i;
  3686. const wrapAdFuncs = {
  3687. apply(fun, that, args) {
  3688. let module = args[0];
  3689. if (typeof module === 'string')
  3690. if ((advModuleNamesStartWith.test(module) ||
  3691. advModuleNamesGeneric.test(module)) &&
  3692. // fix for e.mail.ru in Fx56 and below, looks like Proxy is quirky there
  3693. !module.startsWith('patron.v2.')) {
  3694. let main = args[args.length - 1];
  3695. main._name = module;
  3696. args[args.length - 1] = new Proxy(main, redefiner);
  3697. }
  3698. return _apply(fun, that, args);
  3699. }
  3700. };
  3701. const wrapDefine = def => {
  3702. if (!def)
  3703. return;
  3704. _console.log('define =', def);
  3705. def = new Proxy(def, wrapAdFuncs);
  3706. def._name = 'define';
  3707. return def;
  3708. };
  3709. let _define = wrapDefine(win.define);
  3710. Object.defineProperty(win, 'define', {
  3711. get() {
  3712. return _define;
  3713. },
  3714. set(x) {
  3715. if (_define === x)
  3716. return true;
  3717. _define = wrapDefine(x);
  3718. return true;
  3719. }
  3720. });
  3721. }
  3722.  
  3723. let _honeyPot;
  3724.  
  3725. function defineDetector(mr) {
  3726. let __ = mr._ || {};
  3727. let setHoneyPot = o => {
  3728. if (!o || o === _honeyPot) return;
  3729. _console.log('[honeyPot]', o);
  3730. _honeyPot = function () {
  3731. this.check = new Proxy(() => {
  3732. __.STUCK_IN_POT = false;
  3733. return false;
  3734. }, logger);
  3735. this.check._name = 'honeyPot.check';
  3736. this.destroy = () => null;
  3737. };
  3738. };
  3739. if ('honeyPot' in mr)
  3740. setHoneyPot(mr.honeyPot);
  3741. else
  3742. Object.defineProperty(mr, 'honeyPot', {
  3743. get() {
  3744. return _honeyPot;
  3745. },
  3746. set: setHoneyPot
  3747. });
  3748.  
  3749. __ = new Proxy(__, {
  3750. get(target, prop) {
  3751. return target[prop];
  3752. },
  3753. set(target, prop, val) {
  3754. _console.log(`mr._.${prop} =`, val);
  3755. target[prop] = val;
  3756. return true;
  3757. }
  3758. });
  3759. mr._ = __;
  3760. }
  3761.  
  3762. function defineAdd(mr) {
  3763. let _add;
  3764. let addWrapper = {
  3765. apply(fun, that, args) {
  3766. let module = args[0];
  3767. if (typeof module === 'string' && module.startsWith('ad')) {
  3768. _console.log('Skip module:', module);
  3769. return;
  3770. }
  3771. if (typeof module === 'object' && module.name.startsWith('ad'))
  3772. _console.log('Loaded module:', module);
  3773. return logger.apply(fun, that, args);
  3774. }
  3775. };
  3776. let setMrAdd = v => {
  3777. if (!v) return;
  3778. v._name = 'mr.add';
  3779. v = new Proxy(v, addWrapper);
  3780. _add = v;
  3781. };
  3782. if ('add' in mr)
  3783. setMrAdd(mr.add);
  3784. Object.defineProperty(mr, 'add', {
  3785. get() {
  3786. return _add;
  3787. },
  3788. set: setMrAdd
  3789. });
  3790.  
  3791. }
  3792.  
  3793. const _mr_wrapper = vl => {
  3794. defineLocator(vl.mimic ? vl.mimic : vl);
  3795. defineDetector(vl);
  3796. defineAdd(vl);
  3797. return vl;
  3798. };
  3799. if ('mr' in win) {
  3800. _console.log('Found existing "mr" object.');
  3801. win.mr = _mr_wrapper(win.mr);
  3802. } else {
  3803. let _mr;
  3804. Object.defineProperty(win, 'mr', {
  3805. get() {
  3806. return _mr;
  3807. },
  3808. set(vl) {
  3809. _mr = vl ? _mr_wrapper(vl) : vl;
  3810. },
  3811. configurable: true
  3812. });
  3813. let _defineProperty = _bindCall(Object.defineProperty);
  3814. Object.defineProperty = function defineProperty(...args) {
  3815. const [obj, name, conf] = args;
  3816. if (name === 'mr' && obj instanceof Window) {
  3817. _console.trace('Object.defineProperty(', ...args, ')');
  3818. conf.set(_mr_wrapper(conf.get()));
  3819. }
  3820. if ((name === 'honeyPot' || name === 'add') && _mr === obj && conf.set)
  3821. return;
  3822. return _defineProperty(this, ...args);
  3823. };
  3824. }
  3825. }, nullTools, selectiveCookies, abortExecution)
  3826. },
  3827.  
  3828. 'oms.matchat.online': () => scriptLander(() => {
  3829. let _rmpGlobals;
  3830. Object.defineProperty(win, 'rmpGlobals', {
  3831. get() {
  3832. return _rmpGlobals;
  3833. },
  3834. set(val) {
  3835. if (val === _rmpGlobals)
  3836. return true;
  3837. _rmpGlobals = new Proxy(val, {
  3838. get(obj, name) {
  3839. if (name === 'adBlockerDetected')
  3840. return false;
  3841. return obj[name];
  3842. },
  3843. set(obj, name, val) {
  3844. if (name === 'adBlockerDetected')
  3845. _console.trace('rmpGlobals.adBlockerDetected =', val);
  3846. else
  3847. obj[name] = val;
  3848. return true;
  3849. }
  3850. });
  3851. }
  3852. });
  3853. }),
  3854.  
  3855. 'megogo.net': {
  3856. now() {
  3857. nt.define('adBlock', false);
  3858. nt.define('showAdBlockMessage', nt.func(null, 'showAdBlockMessage'));
  3859. }
  3860. },
  3861.  
  3862. 'naruto-base.su': () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i),
  3863.  
  3864. 'otzovik.com': () => scriptLander(() => {
  3865. abortExecution.onGet('Object.prototype.DirectManagerStart');
  3866. abortExecution.onGet('Object.prototype._visibilityConfirmer');
  3867. let _o_math = win.o_math;
  3868. Object.defineProperty(win, 'o_math', {
  3869. get() {
  3870. return _o_math;
  3871. },
  3872. set(val) {
  3873. delete val.ext_uid;
  3874. _o_math = val;
  3875. }
  3876. });
  3877. }, abortExecution, selectiveCookies),
  3878.  
  3879. 'overclockers.ru': {
  3880. now() {
  3881. abortExecution.onAll('cardinals');
  3882. abortExecution.inlineScript('Document.prototype.createElement', {
  3883. pattern: /mamydirect/
  3884. });
  3885. }
  3886. },
  3887.  
  3888. 'peka2.tv': () => {
  3889. let bodyClass = 'body--branding';
  3890. let checkNode = node => {
  3891. for (let className of node.classList)
  3892. if (className.includes('banner') || className === bodyClass) {
  3893. _removeAttribute(node, 'style');
  3894. node.classList.remove(className);
  3895. for (let attr of Array.from(node.attributes))
  3896. if (attr.name.startsWith('advert'))
  3897. _removeAttribute(node, attr.name);
  3898. }
  3899. };
  3900. (new MutationObserver(ms => {
  3901. let m, node;
  3902. for (m of ms)
  3903. for (node of m.addedNodes)
  3904. if (node instanceof HTMLElement)
  3905. checkNode(node);
  3906. })).observe(_de, {
  3907. childList: true,
  3908. subtree: true
  3909. });
  3910. (new MutationObserver(ms => {
  3911. for (let m of ms)
  3912. checkNode(m.target);
  3913. })).observe(_de, {
  3914. attributes: true,
  3915. subtree: true,
  3916. attributeFilter: ['class']
  3917. });
  3918. },
  3919.  
  3920. 'pikabu.ru': () => gardener('.story', /story__author[^>]+>ads</i, {
  3921. root: '.inner_wrap',
  3922. observe: true
  3923. }),
  3924.  
  3925. 'piratbit.tld': {
  3926. other: 'pb.wtf',
  3927. dom() {
  3928. const remove = node => node && node.parentNode && (_console.log('removed', node), node.parentNode.removeChild(node));
  3929. const isAdLink = el => location.hostname === el.hostname && /^\/(\w{3}|exit|out)\/[\w=/]{20,}$/.test(el.pathname);
  3930. // line above topic content and images in the slider in the header
  3931. for (let el of _document.querySelectorAll('.releas-navbar div a, #page_contents a'))
  3932. if (isAdLink(el))
  3933. remove(el.closest('tr[class]:not(.top_line):not(.active), .row2[id^="post_"]') || el.closest('div[style]:not(.row1):not(.btn-group)'));
  3934. }
  3935. },
  3936.  
  3937. 'pixelexperience.org': () => scriptLander(() => {
  3938. abortExecution.inlineScript('eval', {
  3939. pattern: /blockadblock/
  3940. });
  3941. }, abortExecution),
  3942.  
  3943. 'player.starlight.digital': () => scriptLander(() => {
  3944. let _currVideo = win.currVideo;
  3945. Object.defineProperty(win, 'currVideo', {
  3946. get() {
  3947. return _currVideo;
  3948. },
  3949. set(val) {
  3950. _console.log('currVideo =', val);
  3951. if ('adv' in val)
  3952. val.adv.creatives = [];
  3953. if ('showadv' in val)
  3954. val.showadv = false;
  3955. if ('mediaHls' in val)
  3956. val.mediaHls = val.mediaHls.replace('adv=1', 'adv=0');
  3957. if ('media' in val)
  3958. for (let media of val.media)
  3959. media.url = media.url.replace('adv=1', 'adv=0');
  3960. _currVideo = val;
  3961. }
  3962. });
  3963. }, nullTools),
  3964.  
  3965. 'qrz.ru': {
  3966. now() {
  3967. nt.define('ab', false);
  3968. nt.define('tryMessage', nt.func(null, 'tryMessage'));
  3969. }
  3970. },
  3971.  
  3972. 'rambler.ru': {
  3973. other: [
  3974. 'championat.com', 'eda.ru', 'gazeta.ru', 'lenta.ru', 'letidor.ru', 'media.eagleplatform.com',
  3975. 'motor.ru', 'passion.ru', 'quto.ru', 'rns.online', 'wmj.ru'
  3976. ].join(','),
  3977. now() {
  3978. scriptLander(() => {
  3979. selectiveCookies('detect_count');
  3980. // Prevent autoplay
  3981. const autoList = new Set(['autoplay', 'scrollplay']);
  3982. /* jshint -W001 */
  3983. win.Object.prototype.hasOwnProperty = new Proxy(win.Object.prototype.hasOwnProperty, {
  3984. apply(fun, that, args) {
  3985. if (autoList.has(args[0]))
  3986. return false;
  3987. return _apply(fun, that, args);
  3988. }
  3989. });
  3990. /* jshint +W001 */
  3991. if (location.hostname.endsWith('.media.eagleplatform.com')) {
  3992. const wrapPlayer = player => new Proxy(player, {
  3993. construct(target, args) {
  3994. const player = _construct(target, args);
  3995. if (player.options) {
  3996. nt.defineOn(player.options, 'autoplay', false, 'player.options.');
  3997. nt.defineOn(player.options, 'scroll', false, 'player.options.');
  3998. }
  3999. return player;
  4000. }
  4001. });
  4002. let _EaglePlayer = win.EaglePlayer;
  4003. Object.defineProperty(win, 'EaglePlayer', {
  4004. get() {
  4005. return _EaglePlayer;
  4006. },
  4007. set(player) {
  4008. if (player !== _EaglePlayer)
  4009. _EaglePlayer = wrapPlayer(player);
  4010. return true;
  4011. }
  4012. });
  4013. return;
  4014. }
  4015. // Wrapper for adv loader settings in QW50aS1BZEJsb2Nr['7t7hystz']
  4016. const _contexts = new WeakMap();
  4017. Object.defineProperty(Object.prototype, 'Settings', {
  4018. set(val) {
  4019. if (typeof val === 'object' && 'Transports' in val && 'Urls' in val)
  4020. val.Urls = [];
  4021. _contexts.set(this, val);
  4022. },
  4023. get() {
  4024. return _contexts.get(this);
  4025. }
  4026. });
  4027. // disable video pop-outs in articles on gazeta.ru
  4028. if (location.hostname === 'gazeta.ru' || location.hostname.endsWith('.gazeta.ru'))
  4029. nt.define('creepyVideo', nt.func(null, 'creepyVideo'));
  4030. // disable some logging
  4031. yandexRavenStub();
  4032. // prevent ads from loading
  4033. abortExecution.onGet('g_GazetaNoExchange');
  4034.  
  4035. const blockPatterns = /\[[a-z]{1,4}\("0x[\da-f]+"\)\]|\.(rnet\.plus|24smi\.net|infox\.sg|lentainform\.com)\//i;
  4036. const _setTimeout = win.setTimeout;
  4037. win.setTimeout = function setTimeout(...args) {
  4038. const fun = args[0];
  4039. let str = (typeof fun === 'function' ? _toString(fun) : ''),
  4040. detected = blockPatterns.test(str);
  4041. if (!detected && fun) {
  4042. try {
  4043. str = fun.toString();
  4044. } catch (ignore) {}
  4045. if (str)
  4046. detected = blockPatterns.test(str);
  4047. }
  4048. if (detected) {
  4049. _console.trace(`Stopped setTimeout for: ${str.slice(0,100)}\u2026`);
  4050. return null;
  4051. }
  4052. return _setTimeout(...args);
  4053. };
  4054. }, nullTools, yandexRavenStub, selectiveCookies, abortExecution);
  4055. },
  4056. dom() {
  4057. // disable video pop-outs in articles on lenta.ru and rambler.ru
  4058. let domain = location.hostname.split('.');
  4059. if (['lenta', 'rambler'].includes(domain[domain.length - 2])) {
  4060. const player = _document.querySelector('.js-video-box__container, .j-mini-player__video');
  4061. if (player) player.removeAttribute('class');
  4062. }
  4063. // remove utm_ form links
  4064. const parser = _document.createElement('a');
  4065. _document.addEventListener('mousedown', (e) => {
  4066. let t = e.target;
  4067. if (!t.href)
  4068. t = t.closest('A');
  4069. if (t && t.href) {
  4070. parser.href = t.href;
  4071. let remove = [];
  4072. let params = parser.search.slice(1).split('&').filter(name => {
  4073. if (name.startsWith('utm_')) {
  4074. remove.push(name);
  4075. return false;
  4076. }
  4077. return true;
  4078. });
  4079. if (remove.length)
  4080. _console.log('Removed parameters from link:', ...remove);
  4081. if (params.length)
  4082. parser.search = `?${params.join('&')}`;
  4083. else
  4084. parser.search = '';
  4085. t.href = parser.href;
  4086. }
  4087. }, false);
  4088. }
  4089. },
  4090.  
  4091. 'razlozhi.ru': {
  4092. now() {
  4093. nt.define('cadb', false);
  4094. for (let func of ['createShadowRoot', 'attachShadow'])
  4095. if (func in _Element)
  4096. _Element[func] = function () {
  4097. return this.cloneNode();
  4098. };
  4099. }
  4100. },
  4101.  
  4102. 'rbc.ru': {
  4103. other: 'autonews.ru, rbcplus.ru, sportrbc.ru',
  4104. now() {
  4105. scriptLander(() => selectiveCookies('adb_on'), selectiveCookies);
  4106. let _RA;
  4107. let setArgs = {
  4108. 'showBanners': true,
  4109. 'showAds': true,
  4110. 'banners.staticPath': '',
  4111. 'paywall.staticPath': '',
  4112. 'banners.dfp.config': [],
  4113. 'banners.dfp.pageTargeting': () => null,
  4114. };
  4115. Object.defineProperty(win, 'RA', {
  4116. get() {
  4117. return _RA;
  4118. },
  4119. set(vl) {
  4120. _console.log('RA =', vl);
  4121. if ('repo' in vl) {
  4122. _console.log('RA.repo =', vl.repo);
  4123. vl.repo = new Proxy(vl.repo, {
  4124. set(obj, name, val) {
  4125. if (name === 'banner') {
  4126. _console.log(`RA.repo.${name} =`, val);
  4127. val = new Proxy(val, {
  4128. get(obj, name) {
  4129. let res = obj[name];
  4130. if (typeof obj[name] === 'function') {
  4131. res = () => undefined;
  4132. if (name === 'getService')
  4133. res = service => {
  4134. if (service === 'dfp')
  4135. return {
  4136. getPlaces() {
  4137. return;
  4138. },
  4139. createPlaceholder() {
  4140. return;
  4141. }
  4142. };
  4143. return undefined;
  4144. };
  4145. res.toString = obj[name].toString.bind(obj[name]);
  4146. }
  4147. if (name === 'isInited')
  4148. res = true;
  4149. _console.trace(`get RA.repo.banner.${name}`, res);
  4150. return res;
  4151. }
  4152. });
  4153. }
  4154. obj[name] = val;
  4155. return true;
  4156. }
  4157. });
  4158. } else
  4159. _console.log('Unable to locate RA.repo');
  4160. _RA = new Proxy(vl, {
  4161. set(o, name, val) {
  4162. if (name === 'config') {
  4163. _console.log('RA.config =', val);
  4164. if ('set' in val) {
  4165. val.set = new Proxy(val.set, {
  4166. apply(set, that, args) {
  4167. let name = args[0];
  4168. if (name in setArgs)
  4169. args[1] = setArgs[name];
  4170. if (name in setArgs || name === 'checkad')
  4171. _console.log('RA.config.set(', ...args, ')');
  4172. return _apply(set, that, args);
  4173. }
  4174. });
  4175. val.set('showAds', true); // pretend ads already were shown
  4176. }
  4177. }
  4178. o[name] = val;
  4179. return true;
  4180. }
  4181. });
  4182. }
  4183. });
  4184. Object.defineProperty(win, 'bannersConfig', {
  4185. set() {},
  4186. get() {
  4187. return [];
  4188. }
  4189. });
  4190. // pretend there is a paywall landing on screen already
  4191. let pwl = _document.createElement('div');
  4192. pwl.style.display = 'none';
  4193. pwl.className = 'js-paywall-landing';
  4194. _document.documentElement.appendChild(pwl);
  4195. // detect and skip execution of one of the ABP detectors
  4196. let _setTimeout = win.setTimeout;
  4197. win.setTimeout = function setTimeout(...args) {
  4198. if (typeof args[0] === 'function') {
  4199. let fts = _toString(args[0]);
  4200. if (/\.length\s*>\s*0\s*&&/.test(fts) && /:hidden/.test(fts)) {
  4201. _console.log('Skipped setTimout(', fts, args[1], ')');
  4202. return;
  4203. }
  4204. }
  4205. return _setTimeout(...args);
  4206. };
  4207. // hide banner placeholders
  4208. createStyle('[data-banner-id], .banner__container, .banners__yandex__article { display: none !important }');
  4209. },
  4210. dom() {
  4211. // hide sticky banner place at the top of the page
  4212. for (let itm of _document.querySelectorAll('.l-sticky'))
  4213. if (itm.querySelector('.banner__container__link'))
  4214. itm.style.display = 'none';
  4215. }
  4216. },
  4217.  
  4218. 'reactor.cc': {
  4219. other: 'joyreactor.cc, pornreactor.cc',
  4220. now: () => scriptLander(() => {
  4221. selectiveEval();
  4222. win.open = function () {
  4223. throw new ReferenceError('Redirect prevention.');
  4224. };
  4225. nt.define('Worker', nt.func(nt.proxy({}, 'Worker'), 'Worker'));
  4226. let _CTRManager = win.CTRManager;
  4227. Object.defineProperty(win, 'CTRManager', {
  4228. get() {
  4229. return _CTRManager;
  4230. },
  4231. set(vl) {
  4232. if (vl === _CTRManager)
  4233. return true;
  4234. _CTRManager = {};
  4235. for (let name in vl)
  4236. if (typeof vl[name] !== 'function')
  4237. _CTRManager[name] = vl[name];
  4238. _CTRManager = nt.proxy(_CTRManager, 'CTRManager');
  4239. }
  4240. });
  4241. }, nullTools, selectiveEval),
  4242. click(e) {
  4243. let node = e.target;
  4244. if (node.nodeType === _Node.ELEMENT_NODE &&
  4245. node.style.position === 'absolute' &&
  4246. node.style.zIndex > 0)
  4247. node.parentNode.removeChild(node);
  4248. }
  4249. },
  4250.  
  4251. 'rp5.tld': {
  4252. now() {
  4253. Object.defineProperty(win, 'sContentBottom', {
  4254. set() {},
  4255. get() {
  4256. return '';
  4257. }
  4258. });
  4259. // skip timeout check for blocked requests
  4260. let _setTimeout = win.setTimeout;
  4261. win.setTimeout = function setTimeout(...args) {
  4262. let str = (typeof args[0] === 'string' ? args[0] : _toString(args[0]));
  4263. if (str.includes('xvb')) {
  4264. _console.log('Blocked setTimeout for:', str);
  4265. return;
  4266. }
  4267. return _setTimeout(...args);
  4268. };
  4269. },
  4270. dom() {
  4271. let node = selectNodeByTextContent('Разместить текстовое объявление', {
  4272. root: _de.querySelector('#content-wrapper'),
  4273. shallow: true
  4274. });
  4275. if (node)
  4276. node.style.display = 'none';
  4277. }
  4278. },
  4279.  
  4280. 'rsload.net': {
  4281. load() {
  4282. let dis = _document.querySelector('label[class*="cb-disable"]');
  4283. if (dis)
  4284. dis.click();
  4285. },
  4286. click(e) {
  4287. let t = e.target;
  4288. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  4289. t.href = t.href.replace('://', '://rsload.net:rsload.net@');
  4290. }
  4291. },
  4292.  
  4293. 'rustorka.tld': {
  4294. other: [
  4295. 'rustorka.innal.top, rustorka2.innal.top, rustorka3.innal.top',
  4296. 'rustorka4.innal.top, rustorka5.innal.top, rustorka6.innal.top',
  4297. 'rustorka.naylo.top'
  4298. ].join(', '),
  4299. now: () => scriptLander(() => {
  4300. selectiveCookies('~default|(?!(PHPSESSID|__cfduid|announcements|bb_data|bb_t|id|opt_js|shout)$).*');
  4301. selectiveEval(/antiadblock/);
  4302. abortExecution.onGet('ads_script');
  4303. abortExecution.inlineScript('setTimeout', {
  4304. pattern: /("(\\x[0-9A-F]{2})+",\s?){4}/
  4305. });
  4306.  
  4307. const _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4308. const _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4309.  
  4310. if (_cookie && GM.info.scriptHandler) {
  4311. const asyncCookieCleaner = () => {
  4312. GM.cookie.list({
  4313. url: location.href
  4314. }).then(cookies => {
  4315. for (let cookie of (cookies || []))
  4316. if (cookie.name === cookie.value) {
  4317. GM.cookie.delete(cookie);
  4318. _console.log(`Removed cookie: ${cookie.name}=${cookie.value}`);
  4319. }
  4320. });
  4321. };
  4322. _cookie.get = new Proxy(_cookie.get, {
  4323. apply(fun, that, args) {
  4324. asyncCookieCleaner();
  4325. return _apply(fun, that, args);
  4326. }
  4327. });
  4328. _cookie.set = new Proxy(_cookie.set, {
  4329. apply(fun, that, args) {
  4330. _apply(fun, that, args);
  4331. asyncCookieCleaner();
  4332. return true;
  4333. }
  4334. });
  4335. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4336. }
  4337. }, selectiveCookies, abortExecution),
  4338. dom: () => _document.cookie.slice(0, 0)
  4339. },
  4340.  
  4341. 'rutube.ru': () => scriptLander(() => {
  4342. jsonFilter('creative', 'creative.id');
  4343. jsonFilter('interactives', 'interactives.0');
  4344. }, jsonFilter),
  4345.  
  4346. 'sdamgia.ru': () => scriptLander(() => {
  4347. abortExecution.onGet('Object.prototype.getYa');
  4348. abortExecution.onGet('Object.prototype.initYa');
  4349. abortExecution.onGet('Object.prototype.initYaDirect');
  4350. }, abortExecution),
  4351.  
  4352. 'simpsonsua.com.ua': {
  4353. other: 'simpsonsua.tv',
  4354. now: () => scriptLander(() => {
  4355. let _addEventListener = _Document.addEventListener;
  4356. _document.addEventListener = function (event, callback) {
  4357. if (event === 'DOMContentLoaded' && callback.toString().includes('show_warning'))
  4358. return;
  4359. return _addEventListener.apply(this, arguments);
  4360. };
  4361. nt.define('need_warning', 0);
  4362. nt.define('onYouTubeIframeAPIReady', nt.func(null, 'onYouTubeIframeAPIReady'));
  4363. }, nullTools)
  4364. },
  4365.  
  4366. 'smotret-anime-365.ru': () => scriptLander(() => {
  4367. deepWrapAPI(root => {
  4368. const _pause = _bindCall(root.Audio.prototype.pause);
  4369. const _addEventListener = _bindCall(root.Element.prototype.addEventListener);
  4370. let stopper = e => _pause(e.target);
  4371. root.Audio = new Proxy(root.Audio, {
  4372. construct(audio, args) {
  4373. let res = _construct(audio, args);
  4374. _addEventListener(res, 'play', stopper, true);
  4375. return res;
  4376. }
  4377. });
  4378. let _tagName_get = _bindCall(Object.getOwnPropertyDescriptor(_Element, 'tagName').get);
  4379. root.Document.prototype.createElement = new Proxy(root.Document.prototype.createElement, {
  4380. apply(fun, that, args) {
  4381. let res = _apply(fun, that, args);
  4382. if (_tagName_get(res) === 'AUDIO')
  4383. _addEventListener(res, 'play', stopper, true);
  4384. return res;
  4385. }
  4386. });
  4387. });
  4388. }, deepWrapAPI),
  4389.  
  4390. 'spaces.ru': () => {
  4391. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, {
  4392. parent: 'div'
  4393. });
  4394. gardener('.js-banner_rotator', /./, {
  4395. parent: '.widgets-group'
  4396. });
  4397. },
  4398.  
  4399. 'spam-club.blogspot.co.uk': () => {
  4400. let _clientHeight = Object.getOwnPropertyDescriptor(_Element, 'clientHeight'),
  4401. _clientWidth = Object.getOwnPropertyDescriptor(_Element, 'clientWidth');
  4402. let wrapGetter = (getter) => {
  4403. let _getter = getter;
  4404. return function () {
  4405. let _size = _getter.apply(this, arguments);
  4406. return _size ? _size : 1;
  4407. };
  4408. };
  4409. _clientHeight.get = wrapGetter(_clientHeight.get);
  4410. _clientWidth.get = wrapGetter(_clientWidth.get);
  4411. Object.defineProperty(_Element, 'clientHeight', _clientHeight);
  4412. Object.defineProperty(_Element, 'clientWidth', _clientWidth);
  4413. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  4414. _set_onload = _onload.set;
  4415. _onload.set = function () {
  4416. if (this instanceof HTMLImageElement)
  4417. return true;
  4418. _set_onload.apply(this, arguments);
  4419. };
  4420. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  4421. },
  4422.  
  4423. 'sport-express.ru': () => gardener('.js-relap__item', />Реклама\s+<\//, {
  4424. root: '.container',
  4425. observe: true
  4426. }),
  4427.  
  4428. 'sports.ru': {
  4429. other: 'tribuna.com',
  4430. now() {
  4431. // extra functionality: shows/hides panel at the top depending on scroll direction
  4432. createStyle({
  4433. '.user-panel__fixed': {
  4434. transition: 'top 0.2s ease-in-out!important'
  4435. },
  4436. '.popup__overlay.feedback': {
  4437. display: 'none!important'
  4438. },
  4439. '.user-panel-up': {
  4440. top: '-40px!important'
  4441. },
  4442. '#branding-layout': {
  4443. margin_top: '100px!important'
  4444. }
  4445. }, {
  4446. id: 'fixes',
  4447. protect: false
  4448. });
  4449. scriptLander(() => {
  4450. yandexRavenStub();
  4451. webpackJsonpFilter(/AdBlockDetector|addBranding|loadPlista/);
  4452. }, nullTools, yandexRavenStub, webpackJsonpFilter);
  4453. },
  4454. dom() {
  4455. (function lookForPanel() {
  4456. let panel = _document.querySelector('.user-panel__fixed');
  4457. if (!panel)
  4458. setTimeout(lookForPanel, 100);
  4459. else
  4460. window.addEventListener(
  4461. 'wheel',
  4462. function (e) {
  4463. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  4464. panel.classList.add('user-panel-up');
  4465. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  4466. panel.classList.remove('user-panel-up');
  4467. }, false
  4468. );
  4469. })();
  4470. }
  4471. },
  4472. 'stealthz.ru': {
  4473. dom() {
  4474. // skip timeout
  4475. let $ = _document.querySelector.bind(_document);
  4476. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  4477. if (!timer_1 || !timer_2)
  4478. return;
  4479. timer_1.style.display = 'none';
  4480. timer_2.style.display = 'block';
  4481. }
  4482. },
  4483.  
  4484. 'tortuga.wtf': () => {
  4485. nt.define('Object.prototype.hideab', undefined);
  4486. },
  4487.  
  4488. 'tv.animebest.org': {
  4489. now() {
  4490. let _eval = win.eval;
  4491. win.eval = new win.Proxy(win.eval, {
  4492. apply(evl, ths, args) {
  4493. if (typeof args[0] === 'string' &&
  4494. args[0].includes("'VASTP'")) {
  4495. args[0] = args[0].replace("'VASTP'", "''");
  4496. win.eval = _eval;
  4497. }
  4498. return Reflect.apply(evl, ths, args);
  4499. }
  4500. });
  4501. }
  4502. },
  4503.  
  4504. 'tv-kanali.online': () => {
  4505. win.setTimeout = new Proxy(win.setTimeout, {
  4506. apply(fun, that, args) {
  4507. if (args[0].name && args[0].name.includes('doAd'))
  4508. return;
  4509. if (args[1] === 30000) args[1] = 100;
  4510. return _apply(fun, that, args);
  4511. }
  4512. });
  4513. },
  4514.  
  4515. 'video.khl.ru': () => {
  4516. let props = new Set(['detectBlockers', 'detectBlockersByLink', 'detectBlockersByElement']);
  4517. win.Object.defineProperty = new Proxy(win.Object.defineProperty, {
  4518. apply(def, that, args) {
  4519. if (props.has(args[1])) {
  4520. args[2] = {
  4521. key: args[1],
  4522. value() {
  4523. _console.log(`Skipped ${args[1]} call.`);
  4524. }
  4525. };
  4526. _console.log(`Replaced method ${args[1]}.`);
  4527. }
  4528. return Reflect.apply(def, that, args);
  4529. }
  4530. });
  4531. },
  4532.  
  4533. 'xatab-repack.net': {
  4534. other: 'rg-mechanics.org',
  4535. now() {
  4536. abortExecution.onSet('blocked');
  4537. }
  4538. },
  4539.  
  4540. 'xittv.net': () => scriptLander(() => {
  4541. let logNames = ['setup', 'trigger', 'on', 'off', 'onReady', 'onError', 'getConfig', 'addPlugin', 'getAdBlock'];
  4542. let skipEvents = ['adComplete', 'adSkipped', 'adBlock', 'adRequest', 'adMeta', 'adImpression', 'adError', 'adTime', 'adStarted', 'adClick'];
  4543. let _jwplayer;
  4544. Object.defineProperty(win, 'jwplayer', {
  4545. get() {
  4546. return _jwplayer;
  4547. },
  4548. set(x) {
  4549. _jwplayer = new Proxy(x, {
  4550. apply(fun, that, args) {
  4551. let res = fun.apply(that, args);
  4552. res = new Proxy(res, {
  4553. get(obj, name) {
  4554. if (logNames.includes(name) && typeof obj[name] === 'function')
  4555. return new Proxy(obj[name], {
  4556. apply(fun, that, args) {
  4557. if (name === 'setup') {
  4558. let o = args[0];
  4559. if (o)
  4560. delete o.advertising;
  4561. }
  4562. if (name === 'on' || name === 'trigger') {
  4563. let events = typeof args[0] === 'string' ? args[0].split(" ") : null;
  4564. if (events.length === 1 && skipEvents.includes(events[0]))
  4565. return res;
  4566. if (events.length > 1) {
  4567. let names = [];
  4568. for (let event of events)
  4569. if (!skipEvents.includes(event))
  4570. names.push(event);
  4571. if (names.length > 0)
  4572. args[0] = names.join(" ");
  4573. else
  4574. return res;
  4575. }
  4576. }
  4577. let subres = fun.apply(that, args);
  4578. _console.trace(`jwplayer().${name}(`, ...args, `) >>`, res);
  4579. return subres;
  4580. }
  4581. });
  4582. return obj[name];
  4583. }
  4584. });
  4585. return res;
  4586. }
  4587. });
  4588. _console.log('jwplayer =', x);
  4589. }
  4590. });
  4591. }),
  4592.  
  4593. 'yandex.tld': {
  4594. other: 'yandexsport.tld',
  4595. now: () => {
  4596. // Generic Yandex Scripts
  4597. const mainScript = () => {
  4598. // ads on afisha.yandex.ru, however it looks like selectiveEval isn't perfect
  4599. // since eval could be called in scope to access properties of that scope and
  4600. // such calls with it active break functionality on metrika.yandex.ru
  4601. if (location.hostname.startsWith('afisha.'))
  4602. selectiveEval(/AdvManagerStatic/);
  4603. selectiveCookies();
  4604.  
  4605. let nt = new nullTools({
  4606. log: false,
  4607. trace: true
  4608. });
  4609.  
  4610. // remove banner on the start page
  4611. let AwapsJsonAPI_Json = function (...args) {
  4612. _console.log('>> new AwapsJsonAPI.Json(', ...args, ')');
  4613. };
  4614. AwapsJsonAPI_Json.prototype.checkBannerVisibility = nt.func(true, 'AwapsJsonAPI.Json.checkBannerVisibility');
  4615. AwapsJsonAPI_Json.prototype.addIframeContent = nt.proxy(function (...args) {
  4616. try {
  4617. let frame = args[1][0].parentNode;
  4618. frame.parentNode.removeChild(frame);
  4619. _console.log(`Removed banner placeholder.`);
  4620. } catch (ignore) {
  4621. _console.log(`Can't locate frame object to remove.`);
  4622. }
  4623. });
  4624. AwapsJsonAPI_Json.prototype.getHTML = nt.func('', 'AwapsJsonAPI.Json.getHTML');
  4625. AwapsJsonAPI_Json.prototype = nt.proxy(AwapsJsonAPI_Json.prototype, 'AwapsJsonAPI.Json.prototype');
  4626. AwapsJsonAPI_Json = nt.proxy(AwapsJsonAPI_Json);
  4627. if ('AwapsJsonAPI' in win) {
  4628. _console.log('Oops! AwapsJsonAPI already defined.');
  4629. let f = win.AwapsJsonAPI.Json;
  4630. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  4631. if (f && f.prototype)
  4632. f.prototype = AwapsJsonAPI_Json.prototype;
  4633. } else
  4634. nt.define('AwapsJsonAPI', nt.proxy({
  4635. Json: AwapsJsonAPI_Json
  4636. }));
  4637.  
  4638. let parseExport = x => {
  4639. if (!x)
  4640. return x;
  4641. // remove banner placeholder
  4642. if (x.banner && x.banner.cls && x.banner.cls.banner__parent) {
  4643. let hide = pattern => {
  4644. for (let banner of _document.querySelectorAll(pattern)) {
  4645. _setAttribute(banner, 'style', 'display:none!important');
  4646. _console.log('Hid banner placeholder.');
  4647. }
  4648. };
  4649. let _parent = `.${x.banner.cls.banner__parent}`;
  4650. hide(_parent);
  4651. _document.addEventListener('DOMContentLoaded', () => hide(_parent), false);
  4652. }
  4653.  
  4654. // remove banner data and some other stuff
  4655. delete x.banner;
  4656. delete x.consistency;
  4657. delete x['i-bannerid'];
  4658. delete x['i-counter'];
  4659. delete x['promo-curtain'];
  4660.  
  4661. // remove parts of ga-counter (complete removal break "ТВ Онлайн")
  4662. if (x['ga-counter'] && x['ga-counter'].data) {
  4663. x['ga-counter'].data.id = 0;
  4664. delete x['ga-counter'].data.ether;
  4665. delete x['ga-counter'].data.iframeSrc;
  4666. delete x['ga-counter'].data.iframeSrcEx;
  4667. }
  4668.  
  4669. // remove adblock detector parameters and clean up detector cookie
  4670. if ('adb' in x) {
  4671. let cookie = x.adb.data ? x.adb.data.cookie : undefined;
  4672. if (cookie) {
  4673. selectiveCookies(cookie);
  4674. x.adb.data.adb = 0;
  4675. }
  4676. delete x.adb;
  4677. }
  4678.  
  4679. return x;
  4680. };
  4681. // Yandex banner on main page and some other things
  4682. let _home = win.home,
  4683. _home_set = !!_home;
  4684. Object.defineProperty(win, 'home', {
  4685. get() {
  4686. return _home;
  4687. },
  4688. set(vl) {
  4689. if (!_home_set && vl === _home)
  4690. return;
  4691. _home_set = false;
  4692. _console.log('home =', vl);
  4693. let _home_export = parseExport(vl.export);
  4694. Object.defineProperty(vl, 'export', {
  4695. get() {
  4696. return _home_export;
  4697. },
  4698. set(vl) {
  4699. _home_export = parseExport(vl);
  4700. }
  4701. });
  4702. _home = vl;
  4703. }
  4704. });
  4705.  
  4706. // adblock circumvention on some Yandex domains
  4707. yandexRavenStub();
  4708.  
  4709. // code specific for /news/ and /sport/
  4710. const isNews = location.pathname.startsWith('/news/');
  4711. const isSport = location.pathname.startsWith('/sport/');
  4712. if (isNews || isSport) {
  4713. abortExecution.onGet('yaads.adRenderedCount');
  4714. let AdvertPartner = nt.func(false, 'AdvertPartner');
  4715. nt.defineOn(AdvertPartner, 'defaultProps', {}, 'AdvertPartner.');
  4716. nt.defineOn(AdvertPartner, 'contextTypes', [], 'AdvertPartner.');
  4717. nt.define('Object.prototype.AdvertPartner', AdvertPartner);
  4718. }
  4719. if (isNews)
  4720. createStyle('.mg-grid__row > .mg-grid__col:last-child > .mg-sticky:first-child { display: none !important }');
  4721. if (isSport)
  4722. createStyle('.sport-advert_type_card { display: none !important }');
  4723.  
  4724. // ads in videoplayer
  4725. if (location.pathname.startsWith('/embed/')) {
  4726. let _Sandbox;
  4727. const _define = Object.defineProperty;
  4728. _define(win, 'Sandbox', {
  4729. get() {
  4730. return _Sandbox;
  4731. },
  4732. set(val) {
  4733. if (val && val !== _Sandbox) {
  4734. let _decl = val.decl,
  4735. _init = val.init;
  4736. _define(val, 'init', {
  4737. get() {
  4738. return _init;
  4739. },
  4740. set(init) {
  4741. _init = new Proxy(init, {
  4742. apply(fun, that, args) {
  4743. let cfg = args[0];
  4744. if ('ad_config_json' in cfg)
  4745. cfg.ad_config_json = '{}';
  4746. if ('ad_genre_json' in cfg)
  4747. cfg.ad_config_json = '[]';
  4748. if ('ad_genre_json_hash' in cfg)
  4749. cfg.ad_genre_json_hash = '{ad_genre_json_hash}';
  4750. if ('with_ad_insertion' in cfg)
  4751. cfg.with_ad_insertion = 'false';
  4752. if ('tracking_events' in cfg)
  4753. cfg.tracking_events = {};
  4754. return _apply(fun, that, args);
  4755. }
  4756. });
  4757. }
  4758. });
  4759. _define(val, 'decl', {
  4760. get() {
  4761. return _decl;
  4762. },
  4763. set(decl) {
  4764. _decl = new Proxy(decl, {
  4765. apply(fun, that, args) {
  4766. let cfg = args[0];
  4767. if ('_getAdConfig' in cfg)
  4768. cfg._getAdConfig = new Proxy(cfg._getAdConfig, {
  4769. apply(fun, that, args) {
  4770. let res = _apply(fun, that, args);
  4771. if (res.hasPreroll)
  4772. res.hasPreroll = false;
  4773. return res;
  4774. }
  4775. });
  4776. return _apply(fun, that, args);
  4777. }
  4778. });
  4779. }
  4780. });
  4781. }
  4782. _Sandbox = val;
  4783. }
  4784. });
  4785. }
  4786. // abp detector cookie on yandex pogoda and afisha
  4787. win.Element.prototype.getAttribute = new Proxy(win.Element.prototype.getAttribute, {
  4788. apply(get, el, args) {
  4789. let res = _apply(get, el, args);
  4790. if (res && res.length > 20 && el instanceof HTMLBodyElement)
  4791. try {
  4792. let o = JSON.parse(res),
  4793. found = false,
  4794. check;
  4795. for (let prop in o) {
  4796. check = 'param' in o[prop] || 'aabCookieName' in o[prop];
  4797. if (check || 'banners' in o[prop]) {
  4798. found = true;
  4799. if (check)
  4800. selectiveCookies(o[prop].param || o[prop].aabCookieName);
  4801. _console.log(el.tagName, o, 'removed', o[prop]);
  4802. delete o[prop];
  4803. }
  4804. }
  4805. if (!found) _console.log(el.tagName, o);
  4806. res = JSON.stringify(o);
  4807. } catch (ignore) {}
  4808. return res;
  4809. }
  4810. });
  4811. };
  4812. scriptLander(mainScript, nullTools, yandexRavenStub, abortExecution, selectiveCookies, selectiveEval);
  4813.  
  4814. if ('attachShadow' in _Element) try {
  4815. let fakeRoot = () => ({
  4816. firstChild: null,
  4817. appendChild() {
  4818. return null;
  4819. },
  4820. querySelector() {
  4821. return null;
  4822. },
  4823. querySelectorAll() {
  4824. return null;
  4825. }
  4826. });
  4827. _Element.createShadowRoot = fakeRoot;
  4828. let shadows = new WeakMap();
  4829. let _attachShadow = Object.getOwnPropertyDescriptor(_Element, 'attachShadow');
  4830. _attachShadow.value = function () {
  4831. return shadows.set(this, fakeRoot()).get(this);
  4832. };
  4833. Object.defineProperty(_Element, 'attachShadow', _attachShadow);
  4834. let _shadowRoot = Object.getOwnPropertyDescriptor(_Element, 'shadowRoot');
  4835. _shadowRoot.set = () => null;
  4836. _shadowRoot.get = function () {
  4837. return shadows.has(this) ? shadows.get(this) : undefined;
  4838. };
  4839. Object.defineProperty(_Element, 'shadowRoot', _shadowRoot);
  4840. } catch (e) {
  4841. _console.warn('Unable to wrap Element.prototype.attachShadow\n', e);
  4842. }
  4843.  
  4844. // Disable banner styleSheet (on main page)
  4845. document.addEventListener('DOMContentLoaded', () => {
  4846. for (let sheet of document.styleSheets)
  4847. try {
  4848. for (let rule of sheet.cssRules)
  4849. if (rule.cssText.includes(' 728px 90px')) {
  4850. rule.parentStyleSheet.disabled = true;
  4851. _console.log('Disabled banner styleSheet:', rule.parentStyleSheet);
  4852. }
  4853. } catch (ignore) {}
  4854. }, false);
  4855.  
  4856. // Subdomain-specific Yandex scripts
  4857. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  4858.  
  4859. // Yandex Mail ads
  4860. if (subDomain === 'mail') {
  4861. let wrap = vl => {
  4862. if (!vl)
  4863. return vl;
  4864. _console.log('Daria =', vl);
  4865. nt.defineOn(vl, 'AdBlock', nt.proxy({
  4866. detect: nt.func(new Promise(() => null), 'Daria.AdBlock.detect'),
  4867. enabled: false
  4868. }), 'Daria.');
  4869. nt.defineOn(vl, 'AdvPresenter', nt.proxy({
  4870. _config: nt.proxy({
  4871. banner: false,
  4872. done: false,
  4873. line: false
  4874. })
  4875. }), 'Daria.');
  4876. if (vl.Config) {
  4877. delete vl.Config.adBlockDetector;
  4878. delete vl.Config['adv-url'];
  4879. delete vl.Config.cryprox;
  4880. if (vl.Config.features) {
  4881. delete vl.Config.features.web_adloader_with_cookie_cache;
  4882. delete vl.Config.features.web_ads;
  4883. delete vl.Config.features.web_ads_mute;
  4884. }
  4885. vl.Config.mayHaveAdv = false;
  4886. }
  4887. return vl;
  4888. };
  4889. let _Daria = wrap(win.Daria);
  4890. if (_Daria)
  4891. _console.log('Wrapped already existing object "Daria".');
  4892. Object.defineProperty(win, 'Daria', {
  4893. get() {
  4894. return _Daria;
  4895. },
  4896. set(vl) {
  4897. if (vl === _Daria)
  4898. return;
  4899. _Daria = wrap(vl);
  4900. }
  4901. });
  4902. }
  4903.  
  4904. // Detector and ads on Yandex Music
  4905. if (subDomain === 'music') {
  4906. nt.define('tryPay', nt.func(null, 'tryPay'));
  4907. nt.define('Object.prototype.initMegabannerAPI', nt.func(null, 'initMegabannerAPI'));
  4908. nt.define('Object.prototype.mediaAd', undefined);
  4909. nt.define('Object.prototype.detect', () => new Promise(() => null));
  4910. nt.define('Object.prototype.loadContext', () => new Promise(r => r()));
  4911. nt.define('Object.prototype.antiAdbSetup', nt.func(null, 'ya.music.antiAdbSetup'));
  4912. }
  4913.  
  4914. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  4915. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  4916. // prevent/defuse adblock detector and cleanup localStorage
  4917. for (let name in localStorage)
  4918. if (name.startsWith('videoplayer-ad-session-') || ['ic', 'yu', 'ludca', 'test'].includes(name))
  4919. localStorage.removeItem(name);
  4920. nt.define('localStorage._mt__data', '');
  4921. nt.define('localStorage.yandexJSPlayerApiSavedSingleVideoSessionWatchedTimeSinceAd', Math.random() * 1000);
  4922.  
  4923. // cookie cleaner
  4924. let yp_keepCookieParts = /\.(sp|ygo|ygu)\./; // ygo = city id; ygu = detect city automatically
  4925. let _doc_proto = ('cookie' in _Document) ? _Document : Object.getPrototypeOf(_document);
  4926. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  4927. if (_cookie) {
  4928. let _set_cookie = _bindCall(_cookie.set);
  4929. _cookie.set = function (value) {
  4930. if (/^(mda=|yp=|ys=|yabs-|__|bltsr=)/.test(value))
  4931. // remove value, set expired
  4932. if (!value.startsWith('yp=')) {
  4933. value = value.replace(/^([^=]+=)[^;]+/, '$1').replace(/(expires=)[\w\s\d,]+/, '$1Thu, 01 Jan 1970 00');
  4934. _console.trace('expire cookie', value.match(/^[^=]+/)[0]);
  4935. } else {
  4936. let parts = value.split(';');
  4937. let values = parts[0].split('#').filter(part => yp_keepCookieParts.test(part));
  4938. if (values.length)
  4939. values[0] = values[0].replace(/^yp=/, '');
  4940. let res = `yp=${values.join('#')}`;
  4941. _console.trace(`set cookie ${res}, dropped ${parts[0].replace(res,'')}`);
  4942. parts[0] = res;
  4943. value = parts.join(';');
  4944. }
  4945. return _set_cookie(this, value);
  4946. };
  4947. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  4948. }
  4949. }
  4950. },
  4951. dom: () => {
  4952. { // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  4953. let count = 0,
  4954. lock = false;
  4955. const log = () => {
  4956. count++;
  4957. if (lock)
  4958. return;
  4959. setTimeout(() => {
  4960. _console.log('Removed tracking attributes from', count, 'links.');
  4961. count = 0;
  4962. lock = false;
  4963. }, 3333);
  4964. lock = true;
  4965. };
  4966. const selectors = (
  4967. 'A[onmousedown*="/jsredir"],' +
  4968. 'A[data-log-node],' +
  4969. 'A[data-vdir-href],' +
  4970. 'A[data-counter]'
  4971. );
  4972. const removeTrackingAttributes = (link) => {
  4973. _removeAttribute(link, 'onmousedown');
  4974. _removeAttribute(link, 'data-log-node');
  4975. // data-vdir-href
  4976. _removeAttribute(link, 'data-vdir-href');
  4977. _removeAttribute(link, 'data-orig-href');
  4978. // data-counter
  4979. _removeAttribute(link, 'data-counter');
  4980. _removeAttribute(link, 'data-bem');
  4981. log();
  4982. };
  4983. const removeTracking = (scope) => {
  4984. if (scope instanceof Element)
  4985. for (let link of scope.querySelectorAll(selectors))
  4986. removeTrackingAttributes(link);
  4987. };
  4988.  
  4989. removeTracking(_document);
  4990. (new MutationObserver(
  4991. function (ms) {
  4992. let m, node;
  4993. for (m of ms)
  4994. for (node of m.addedNodes)
  4995. if (node instanceof HTMLAnchorElement && node.matches(selectors))
  4996. removeTrackingAttributes(node);
  4997. else
  4998. removeTracking(node);
  4999. }
  5000. )).observe(_de, {
  5001. childList: true,
  5002. subtree: true
  5003. });
  5004. }
  5005.  
  5006. // Subdomain-specific Yandex scripts
  5007. const subDomain = location.hostname.slice(0, location.hostname.indexOf('.'));
  5008.  
  5009. // Function to attach an observer to monitor dynamic changes on the page
  5010. const pageUpdateObserver = (func, obj, params) => {
  5011. if (obj)
  5012. (new MutationObserver(func))
  5013. .observe(obj, (params || {
  5014. childList: true,
  5015. subtree: true
  5016. }));
  5017. };
  5018. // Short name for parentNode.removeChild
  5019. const remove = node => {
  5020. if (!node || !node.parentNode)
  5021. return false;
  5022. _console.log('Removed node.');
  5023. node.parentNode.removeChild(node);
  5024. };
  5025. // Short name for setAttribute style to display:none
  5026. const hide = node => {
  5027. if (!node)
  5028. return false;
  5029. _console.log('Hid node.');
  5030. _setAttribute(node, 'style', 'display:none!important');
  5031. };
  5032.  
  5033. if (subDomain === 'music') {
  5034. const removeMusicAds = () => {
  5035. for (let node of _querySelectorAll('.ads-block'))
  5036. remove(node);
  5037. };
  5038. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  5039. removeMusicAds();
  5040. }
  5041.  
  5042. if (subDomain === 'tv') {
  5043. const removeTVAds = () => {
  5044. const yadWord = /Яндекс.Директ/i;
  5045. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  5046. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])')) {
  5047. if (node.offsetWidth) {
  5048. let pad = _document.createElement('div');
  5049. _setAttribute(pad, 'style', `width:${node.offsetWidth}px`);
  5050. node.parentNode.appendChild(pad);
  5051. }
  5052. remove(node);
  5053. }
  5054. };
  5055. pageUpdateObserver(removeTVAds, _document.body);
  5056. removeTVAds();
  5057. }
  5058.  
  5059. const isSearch = /^\/(yand)?search[/?]/i.test(location.pathname);
  5060. if (isSearch) {
  5061. const removeSearchAds = () => {
  5062. const adWords = /Реклама|Ad/i;
  5063. for (let node of _querySelectorAll('.serp-item'))
  5064. if (_getAttribute(node, 'role') === 'complementary' ||
  5065. adWords.test((node.querySelector('.label') || {}).textContent))
  5066. hide(node);
  5067. };
  5068. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  5069. removeSearchAds();
  5070. }
  5071.  
  5072. if (['mail', 'music', 'tv', 'yandexsport'].includes(subDomain) || isSearch) {
  5073. // Generic ads removal and fixes
  5074. for (let node of _querySelectorAll('.serp-header'))
  5075. node.style.marginTop = '0';
  5076. for (let node of _querySelectorAll(
  5077. '.serp-adv__head + .serp-item,' +
  5078. '#adbanner,' +
  5079. '.serp-adv,' +
  5080. '.b-spec-adv,' +
  5081. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  5082. )) remove(node);
  5083. }
  5084. }
  5085. },
  5086.  
  5087. 'yap.ru': {
  5088. other: 'yaplakal.com',
  5089. now() {
  5090. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  5091. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {
  5092. parent: 'tr',
  5093. siblings: -2
  5094. });
  5095. }
  5096. },
  5097.  
  5098. 'yapx.ru': () => scriptLander(() => {
  5099. selectiveCookies('adblock_state|adblock_views');
  5100. nt.define('blockAdBlock', {
  5101. on: nt.func(nt.proxy({}, 'blockAdBlock.on', nt.NULL), 'blockAdBlock.on'),
  5102. check: nt.func(null, 'blockAdBlock.check')
  5103. });
  5104. }, selectiveCookies, nullTools),
  5105.  
  5106. 'youtube.com': () => scriptLander(() => {
  5107. jsonFilter('playerResponse.adPlacements playerResponse.playerAds adPlacements playerAds');
  5108. }, jsonFilter),
  5109.  
  5110. 'znanija.com': () => scriptLander(() => {
  5111. abortExecution.onSet('getAdBlockType');
  5112. }, abortExecution)
  5113. };
  5114.  
  5115. // replace '.tld' in domain names, add alternative domain names if present and wrap functions into objects
  5116. {
  5117. const parts = _document.domain.split('.');
  5118. const tld = /\.tld$/;
  5119. const tldSubstitur = (() => {
  5120. // stores TLD of current domain (simplistic TLD implementation)
  5121. const last = parts.length - 1;
  5122. const tld = ['', parts[last]];
  5123. const secondLevel = [
  5124. 'biz', 'com', 'edu', 'gov', 'info', 'int', 'mil', 'net', 'org', 'pro'
  5125. ];
  5126. // add second from the end part of domain name as part of the TLD substitutor
  5127. // when domain name consists of more than 2 parts and it looks like a part of TLD
  5128. if ((parts[0] !== 'www' && parts.length > 2 || parts.length > 3) &&
  5129. (parts[last - 1].length < 3 || secondLevel.includes(parts[last - 1])))
  5130. tld.splice(0, 1, parts[last - 1]);
  5131. return tld.join('.');
  5132. })();
  5133. for (let name in scripts) {
  5134. if (typeof scripts[name] === 'function')
  5135. scripts[name] = {
  5136. now: scripts[name]
  5137. };
  5138. if (name.endsWith('.tld'))
  5139. scripts[name.replace(tld, tldSubstitur)] = scripts[name];
  5140. for (let domain of (scripts[name].other && scripts[name].other.split(/,\s*/) || [])) {
  5141. domain = domain.replace(tld, tldSubstitur);
  5142. if (domain in scripts)
  5143. _console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  5144. scripts[domain] = scripts[name];
  5145. }
  5146. delete scripts[name].other;
  5147. }
  5148. // scripts lookup
  5149. const windowEvents = ['load', 'unload', 'beforeunload'];
  5150. let domain;
  5151. while (parts.length > 1) {
  5152. domain = parts.join('.');
  5153. if (domain in scripts) {
  5154. for (let when in scripts[domain]) {
  5155. let script = scripts[domain][when];
  5156. if (when === 'now')
  5157. script();
  5158. else if (when === 'dom')
  5159. _document.addEventListener('DOMContentLoaded', script);
  5160. else if (windowEvents.includes(when))
  5161. win.addEventListener(when, scripts[domain][when]);
  5162. else
  5163. _document.addEventListener(when, scripts[domain][when]);
  5164. }
  5165. }
  5166. parts.shift();
  5167. }
  5168. }
  5169.  
  5170. // Batch script lander
  5171. if (!skipLander)
  5172. landScript(batchLand, batchPrepend);
  5173.  
  5174. { // JS Fixes Tools Menu
  5175. const incompatibleScriptHandler = !/^(Tamper|Violent)monkey$/.test(GM.info.scriptHandler) || GM.info.scriptHandler === 'Violentmonkey' && isFirefox;
  5176. // Debug function, lists all unusual window properties
  5177. const isNativeFunction = /^[^{]*\{[\s\r\n]*\[native\scode\][\s\r\n]*\}$/;
  5178. const getStrangeObjectsList = () => {
  5179. _console.group('Window strangers list');
  5180. const _skip = 'frames/self/window/webkitStorageInfo'.split('/');
  5181. for (let n of Object.getOwnPropertyNames(win))
  5182. try {
  5183. let val = win[n];
  5184. if (val && !_skip.includes(n) && (win !== window && val !== window[n] || win === window) &&
  5185. (typeof val !== 'function' || typeof val === 'function' && !isNativeFunction.test(_toString(val))))
  5186. _console.log(`${n} =`, val);
  5187. } catch (e) {
  5188. _console.log(n, 'returns error on read', e);
  5189. }
  5190. _console.groupEnd('Window strangers list');
  5191. };
  5192.  
  5193. const lines = {
  5194. linked: [],
  5195. MenuOptions: {
  5196. eng: 'Options',
  5197. rus: 'Настройки'
  5198. },
  5199. MenuCompatibilityWarning: {
  5200. eng: 'is not supported',
  5201. rus: 'не поддерживается'
  5202. },
  5203. langs: {
  5204. eng: 'English',
  5205. rus: 'Русский'
  5206. },
  5207. sObjBtn: {
  5208. eng: 'List unusual "window" properties in console',
  5209. rus: 'Вывести в консоль нестандартные свойства «window»'
  5210. },
  5211. HeaderTools: {
  5212. eng: 'Tools',
  5213. rus: 'Инструменты'
  5214. },
  5215. HeaderOptions: {
  5216. eng: 'Options',
  5217. rus: 'Настройки'
  5218. },
  5219. AccessStatisticsLabel: {
  5220. eng: 'Display stubs access statistics and JSON filter',
  5221. rus: 'Выводить статистику запросов к заглушкам и JSON фильтра'
  5222. },
  5223. AbortExecutionStatisticsLabel: {
  5224. eng: 'Display abort execution statistics',
  5225. rus: 'Выводить статистику прерывания исполнения скриптов'
  5226. },
  5227. BlockNotificationPermissionRequestsLabel: {
  5228. eng: 'Block requests to Show Notifications on sites',
  5229. rus: 'Блокировать запросы Показывать Уведомления на сайтах'
  5230. },
  5231. ShowScriptHandlerCompatibilityWarningLabel: {
  5232. eng: 'Show compatibility warning in menu next to Options',
  5233. rus: 'Отображать предупреждение о совместимости в меню рядом с Настройками'
  5234. },
  5235. reg(el, name) {
  5236. this[name].link = el;
  5237. this.linked.push(name);
  5238. },
  5239. setLang(lang = 'eng') {
  5240. for (let name of this.linked) {
  5241. const el = this[name].link;
  5242. const label = this[name][lang];
  5243. el.textContent = label;
  5244. }
  5245. this.langs.link.value = lang;
  5246. jsf.Lang = lang;
  5247. }
  5248. };
  5249.  
  5250. const _createTextNode = _Document.createTextNode.bind(_document);
  5251. const createOptionsWindow = () => {
  5252. const root = _createElement('div'),
  5253. shadow = _attachShadow ? _attachShadow(root, {
  5254. mode: 'closed'
  5255. }) : root,
  5256. overlay = _createElement('div'),
  5257. inner = _createElement('div');
  5258.  
  5259. overlay.id = 'overlay';
  5260. overlay.appendChild(inner);
  5261. shadow.appendChild(overlay);
  5262.  
  5263. inner.id = 'inner';
  5264. inner.br = function appendBreakLine() {
  5265. return this.appendChild(_createElement('br'));
  5266. };
  5267.  
  5268. createStyle({
  5269. 'h2': {
  5270. margin_top: 0
  5271. },
  5272. 'h2, h3': {
  5273. margin_block_end: '0.5em'
  5274. },
  5275. 'div, button, select, input': {
  5276. font_family: 'Helvetica, Arial, sans-serif',
  5277. font_size: '12pt'
  5278. },
  5279. 'button': {
  5280. background: 'linear-gradient(to bottom, #f0f0f0 5%, #c0c0c0 100%)',
  5281. border_radius: '3px',
  5282. border: '1px solid #a1a1a1',
  5283. color: '#000000',
  5284. text_shadow: '0px 1px 0px #d4d4d4'
  5285. },
  5286. 'button:hover': {
  5287. background: 'linear-gradient(to bottom, #c0c0c0 5%, #f0f0f0 100%)'
  5288. },
  5289. 'button:active': {
  5290. position: 'relative',
  5291. top: '1px'
  5292. },
  5293. 'select': {
  5294. border: '1px solid darkgrey',
  5295. border_radius: '0px 0px 5px 5px',
  5296. border_top: '0px'
  5297. },
  5298. 'button:focus, select:focus': {
  5299. outline: 'none'
  5300. },
  5301. '#overlay': {
  5302. position: 'fixed',
  5303. top: 0,
  5304. left: 0,
  5305. bottom: 0,
  5306. right: 0,
  5307. background: 'rgba(0,0,0,0.65)',
  5308. z_index: 2147483647 // Highest z-index: Math.pow(2, 31) - 1
  5309. },
  5310. '#inner': {
  5311. background: 'whitesmoke',
  5312. color: 'black',
  5313. padding: '1.5em 1em 1.5em 1em',
  5314. max_width: '150ch',
  5315. position: 'absolute',
  5316. top: '50%',
  5317. left: '50%',
  5318. transform: 'translate(-50%, -50%)',
  5319. border: '1px solid darkgrey',
  5320. border_radius: '5px'
  5321. },
  5322. '#closeOptionsButton': {
  5323. float: 'right',
  5324. transform: 'translate(1em, -1.5em)',
  5325. border: 0,
  5326. border_radius: 0,
  5327. background: 'none',
  5328. box_shadow: 'none'
  5329. },
  5330. '#selectLang': {
  5331. float: 'right',
  5332. transform: 'translate(0, -1.5em)'
  5333. },
  5334. '.optionsLabel': {
  5335. padding_left: '1.5em',
  5336. text_indent: '-1em',
  5337. display: 'block'
  5338. },
  5339. '.optionsCheckbox': {
  5340. left: '-0.25em',
  5341. width: '1em',
  5342. height: '1em',
  5343. padding: 0,
  5344. margin: 0,
  5345. position: 'relative',
  5346. vertical_align: 'middle'
  5347. },
  5348. '@media (prefers-color-scheme: dark)': {
  5349. '#inner': {
  5350. background_color: '#292a2d',
  5351. color: 'white',
  5352. border: '1px solid #1a1b1e'
  5353. },
  5354. 'input': {
  5355. filter: 'invert(100%)'
  5356. },
  5357. 'button': {
  5358. background: 'linear-gradient(to bottom, #575757 5%, #303030 100%)',
  5359. border_color: '#575757',
  5360. color: '#f0f0f0',
  5361. text_shadow: '0px 1px 0px #171717'
  5362. },
  5363. 'button:hover': {
  5364. background: 'linear-gradient(to bottom, #303030 5%, #575757 100%)'
  5365. },
  5366. 'select': {
  5367. background_color: '#303030',
  5368. color: '#f0f0f0',
  5369. border: '1px solid #1a1b1e',
  5370. border_radius: '0px 0px 5px 5px',
  5371. border_top: '0px'
  5372. },
  5373. '#overlay': {
  5374. background: 'rgba(0,0,0,.85)',
  5375. }
  5376. }
  5377. }, {
  5378. root: shadow,
  5379. protect: false
  5380. });
  5381.  
  5382. // components
  5383. function createCheckbox(name) {
  5384. const checkbox = _createElement('input'),
  5385. label = _createElement('label');
  5386. checkbox.type = 'checkbox';
  5387. checkbox.classList.add('optionsCheckbox');
  5388. checkbox.checked = jsf[name];
  5389. checkbox.onclick = e => {
  5390. jsf[name] = e.target.checked;
  5391. return true;
  5392. };
  5393. label.classList.add('optionsLabel');
  5394. label.appendChild(checkbox);
  5395. const text = _createTextNode('');
  5396. label.appendChild(text);
  5397. Object.defineProperty(label, 'textContent', {
  5398. set(title) {
  5399. text.textContent = title;
  5400. }
  5401. });
  5402. return label;
  5403. }
  5404.  
  5405. // language & close
  5406. const closeBtn = _createElement('button');
  5407. closeBtn.onclick = () => _removeChild(root);
  5408. closeBtn.textContent = '\u2715';
  5409. closeBtn.id = 'closeOptionsButton';
  5410. inner.appendChild(closeBtn);
  5411.  
  5412. overlay.addEventListener('click', e => {
  5413. if (e.target === overlay) {
  5414. _removeChild(root);
  5415. e.preventDefault();
  5416. }
  5417. e.stopPropagation();
  5418. }, false);
  5419.  
  5420. const selectLang = _createElement('select');
  5421. for (let name in lines.langs) {
  5422. const langOption = _createElement('option');
  5423. langOption.value = name;
  5424. langOption.innerText = lines.langs[name];
  5425. selectLang.appendChild(langOption);
  5426. }
  5427. selectLang.id = 'selectLang';
  5428. lines.langs.link = selectLang;
  5429. inner.appendChild(selectLang);
  5430.  
  5431. selectLang.onchange = e => {
  5432. const lang = e.target.value;
  5433. lines.setLang(lang);
  5434. };
  5435.  
  5436. // fill options form
  5437. const header = _createElement('h2');
  5438. header.textContent = 'RU AdList JS Fixes';
  5439. inner.appendChild(header);
  5440.  
  5441. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderTools');
  5442.  
  5443. const sObjBtn = _createElement('button');
  5444. sObjBtn.onclick = getStrangeObjectsList;
  5445. sObjBtn.textContent = '';
  5446. lines.reg(inner.appendChild(sObjBtn), 'sObjBtn');
  5447.  
  5448. lines.reg(inner.appendChild(_createElement('h3')), 'HeaderOptions');
  5449.  
  5450. lines.reg(inner.appendChild(createCheckbox('AccessStatistics')), 'AccessStatisticsLabel');
  5451. lines.reg(inner.appendChild(createCheckbox('AbortExecutionStatistics')), 'AbortExecutionStatisticsLabel');
  5452.  
  5453. lines.reg(inner.appendChild(createCheckbox('BlockNotificationPermissionRequests')), 'BlockNotificationPermissionRequestsLabel');
  5454.  
  5455. if (incompatibleScriptHandler) {
  5456. inner.appendChild(_createElement('br'));
  5457. lines.reg(inner.appendChild(createCheckbox('ShowScriptHandlerCompatibilityWarning')), 'ShowScriptHandlerCompatibilityWarningLabel');
  5458. }
  5459.  
  5460. lines.setLang(jsf.Lang);
  5461.  
  5462. return root;
  5463. };
  5464.  
  5465. let optionsWindow;
  5466. GM_registerMenuCommand(lines.MenuOptions[jsf.Lang], () => _appendChild(optionsWindow = optionsWindow || createOptionsWindow()));
  5467. // add warning to script menu for non-Tampermonkey users
  5468. if (jsf.ShowScriptHandlerCompatibilityWarning && incompatibleScriptHandler)
  5469. GM_registerMenuCommand(`${GM.info.scriptHandler} ${lines.MenuCompatibilityWarning[jsf.Lang]}`, () => {
  5470. win.open(`https://greasyfork.org/${opts.Lang.slice(0,2)}/scripts/19993-ru-adlist-js-fixes#additional-info`);
  5471. });
  5472. }
  5473. })();