RU AdList JS Fixes

try to take over the world!

当前为 2020-12-20 提交的版本,查看 最新版本

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