RU AdList JS Fixes

try to take over the world!

目前为 2020-10-07 提交的版本,查看 最新版本

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