RU AdList JS Fixes

try to take over the world!

当前为 2020-10-15 提交的版本,查看 最新版本

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