RU AdList JS Fixes

try to take over the world!

当前为 2018-02-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RU AdList JS Fixes
  3. // @namespace ruadlist_js_fixes
  4. // @version 20180201.1
  5. // @description try to take over the world!
  6. // @author lainverse & dimisa
  7. // @match *://*/*
  8. // @exclude *://*.alfabank.ru/*
  9. // @exclude *://alfabank.ru/*
  10. // @exclude *://*.unicreditbanking.net/*
  11. // @exclude *://unicreditbanking.net/*
  12. // @grant unsafeWindow
  13. // @grant window.close
  14. // @grant GM_getValue
  15. // @grant GM_setValue
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. (function() {
  20. 'use strict';
  21. let win = (unsafeWindow || window),
  22. // http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
  23. isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0,
  24. isChrome = !!window.chrome && !!window.chrome.webstore,
  25. isSafari = (Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 ||
  26. (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window.safari || safari.pushNotification)),
  27. isFirefox = typeof InstallTrigger !== 'undefined',
  28. inIFrame = (win.self !== win.top),
  29. _getAttribute = Element.prototype.getAttribute,
  30. _setAttribute = Element.prototype.setAttribute,
  31. _removeAttribute = Element.prototype.removeAttribute,
  32. _de = document.documentElement,
  33. _appendChild = Document.prototype.appendChild.bind(_de),
  34. _removeChild = Document.prototype.removeChild.bind(_de),
  35. _createElement = Document.prototype.createElement.bind(document);
  36.  
  37. if (isFirefox && // Exit on image pages in Fx
  38. document.constructor.prototype.toString() === '[object ImageDocumentPrototype]')
  39. return;
  40.  
  41. // dTree 2.05 in some cases replaces Node object before my script kicks in :(
  42. if (!Node.prototype)
  43. {
  44. let ifr = _createElement('iframe');
  45. _appendChild(ifr);
  46. try {
  47. window.Node = ifr.contentWindow.Node;
  48. console.log('Node object restored. -_-');
  49. } catch(e) {
  50. console.log('Unable to restore Node object.', e);
  51. }
  52. _removeChild(ifr);
  53. }
  54.  
  55. // NodeList iterator polyfill (mostly for Safari)
  56. // https://jakearchibald.com/2014/iterators-gonna-iterate/
  57. if (!NodeList.prototype[Symbol.iterator]) {
  58. NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
  59. }
  60.  
  61. (function initOpts() {
  62. let getGlobal, setGlobal, exit = false;
  63. try {
  64. getGlobal = GM_getValue;
  65. setGlobal = GM_setValue;
  66. } catch (ignore) {
  67. // exit if old GM API is not available
  68. // promise-based equivalents postpone code execution for too long
  69. exit = true;
  70. }
  71.  
  72. // Options
  73. let opts = {
  74. 'useWSIFunc': useWSI
  75. };
  76. if (exit) {
  77. for (let func in opts)
  78. opts[func]();
  79. return;
  80. }
  81.  
  82. {
  83. let optsCall = function(callback)
  84. {
  85. // Register event listener
  86. let key = "optsCallEvent_" + Math.random().toString(36).substr(2),
  87. cb = callback.func.bind(callback.name);
  88. window.addEventListener(key, cb, false);
  89. // Generate and dispatch synthetic event
  90. let ev = document.createEvent("HTMLEvents");
  91. ev.initEvent(key, true, false);
  92. window.dispatchEvent(ev);
  93. // Remove listener
  94. window.removeEventListener(key, cb, false);
  95. };
  96.  
  97. let initOptsHandler = function()
  98. {
  99. opts[this] = getGlobal(this, true);
  100. if (opts[this])
  101. opts[this+'Func']();
  102. };
  103.  
  104. optsCall({
  105. func: initOptsHandler,
  106. name: 'useWSI'
  107. });
  108.  
  109. // show options page
  110. let openOptions = function()
  111. {
  112. let ovl = _createElement('div'),
  113. inner = _createElement('div');
  114. ovl.style = (
  115. 'position: fixed;'+
  116. 'top:0; left:0;'+
  117. 'bottom: 0; right: 0;'+
  118. 'background: rgba(0,0,0,0.85);'+
  119. 'z-index: 2147483647;'+
  120. 'padding: 5em'
  121. );
  122. inner.style = (
  123. 'background: whitesmoke;'+
  124. 'font-size: 10pt;'+
  125. 'color: black;'+
  126. 'padding: 1em'
  127. );
  128. inner.textContent = 'JS Fixes Options: (reload page to apply)';
  129. inner.appendChild(_createElement('br'));
  130. inner.appendChild(_createElement('br'));
  131. ovl.addEventListener(
  132. 'click', function(e)
  133. {
  134. if (e.target === ovl) {
  135. ovl.parentNode.removeChild(ovl);
  136. e.preventDefault();
  137. }
  138. e.stopPropagation();
  139. }, false
  140. );
  141. // append checkbox with label function
  142. function addCheckbox(optName, optLabel)
  143. {
  144. let c = _createElement('input'),
  145. l = _createElement('label');
  146. c.type = 'checkbox';
  147. c.id = optName;
  148. optsCall({
  149. func: function()
  150. {
  151. c.checked = getGlobal(this);
  152. },
  153. name: optName
  154. });
  155. c.addEventListener(
  156. 'click', function(e)
  157. {
  158. optsCall({
  159. func:function(){
  160. setGlobal(this, e.target.checked);
  161. opts[this] = e.target.checked;
  162. },
  163. name:optName
  164. });
  165. }, true
  166. );
  167. l.textContent = optLabel;
  168. l.setAttribute('for', optName);
  169. inner.appendChild(c);
  170. inner.appendChild(l);
  171. inner.appendChild(_createElement('br'));
  172. }
  173. // append checkboxes
  174. addCheckbox('useWSI', 'Use WebSocket filter. Disable if experience problems with WebSocket connections.');
  175.  
  176. let sObjBtn = _createElement('button');
  177. sObjBtn.onclick = getStrangeObjectsList;
  178. sObjBtn.textContent = 'Print (in console) list of unusual window properties';
  179. inner.appendChild(_createElement('br'));
  180. inner.appendChild(sObjBtn);
  181.  
  182. document.body.appendChild(ovl);
  183. ovl.appendChild(inner);
  184. };
  185.  
  186. // monitor keys pressed for Ctrl+Alt+Shift+J > s > f code
  187. let opPos = 0, opKey = ['KeyJ','KeyS','KeyF'];
  188. document.addEventListener(
  189. 'keydown', function(e)
  190. {
  191. if ((e.code === opKey[opPos] || e.location) &&
  192. (!!opPos || e.altKey && e.ctrlKey && e.shiftKey))
  193. {
  194. opPos += e.location ? 0 : 1;
  195. e.stopPropagation();
  196. e.preventDefault();
  197. } else {
  198. opPos = 0;
  199. }
  200. if (opPos === opKey.length)
  201. {
  202. opPos = 0;
  203. openOptions();
  204. }
  205. }, false
  206. );
  207. }
  208. })();
  209.  
  210. // Special wrapper script to run scripts designed to override standard DOM functions
  211. // In Firefox appends supplied script to a page to make it run in page context and let
  212. // page content access overridden functions. In other browsers just run it as-is.
  213. function scriptLander(func, ...prepend)
  214. {
  215. if (!isFirefox)
  216. {
  217. func();
  218. return;
  219. }
  220. let script = _createElement('script');
  221. script.textContent = `(function(){let win=window;${(
  222. (prepend.length > 0 ? prepend.join(';') : '')
  223. )};(${func})();})();`;
  224. _appendChild(script);
  225. _removeChild(script);
  226. }
  227.  
  228. function nullTools(opts) {
  229. // jshint validthis:true
  230. let nt = this;
  231. opts = opts || {};
  232. function log() { if (opts.log) console.log(...arguments); }
  233. function trace() { if (opts.log || opts.trace) console.warn(...arguments); }
  234.  
  235. nt.destroy = function(o, destroy)
  236. {
  237. if (!opts.destroy && !destroy && o instanceof Object)
  238. return;
  239. log('cleaning', o);
  240. try {
  241. for (let item in o)
  242. {
  243. if (item instanceof Object)
  244. nt.destroy(item);
  245. delete o[item];
  246. }
  247. } catch (e) {
  248. log('Error in object destructor', e);
  249. }
  250. };
  251.  
  252. nt.define = function(obj, prop, val, enumerable = true)
  253. {
  254. try {
  255. Object.defineProperty(
  256. obj, prop, {
  257. get: () => val,
  258. set: (v) => (v !== val ? (log(`set ${prop} of`, obj, 'to', v), nt.destroy(v)) : null, undefined),
  259. enumerable: enumerable
  260. }
  261. );
  262. } catch (err) {
  263. console.log(`Unable to redefine "${prop}" in `, obj, err);
  264. }
  265. };
  266. nt.proxy = function(obj)
  267. {
  268. return new Proxy(
  269. obj, {
  270. get: (t, p) => p in t ? t[p] : console.warn(`Missing ${p} in`, t),
  271. set: (t, p, v) => (v !== t[p] ? (log(`set ${p} of`, t, 'to', v), nt.destroy(v)) : null, true)
  272. }
  273. );
  274. };
  275. nt.func = (val, name = '') => () => (trace(`call func ${name}, return`, val), val);
  276. }
  277.  
  278. // Debug function, lists all unusual window properties
  279. function getStrangeObjectsList()
  280. {
  281. console.warn('Strangers list start');
  282. let ifr = document.createElement('iframe');
  283. ifr.onload = () => {
  284. for (let name in win)
  285. if (!(name in ifr.contentWindow))
  286. console.log(name);
  287. };
  288. document.documentElement.appendChild(ifr);
  289. document.documentElement.removeChild(ifr);
  290. console.warn('Strangers list end');
  291. }
  292.  
  293. // Fake objects of advertisement networks to break their workflow
  294. scriptLander(
  295. function()
  296. {
  297. let nt = new nullTools();
  298. // Popular adblock detector
  299. if (!('fuckAdBlock' in win))
  300. {
  301. let FuckAdBlock = function(options) {
  302. let self = this;
  303. self._options = {
  304. checkOnLoad: false,
  305. resetOnEnd: false,
  306. checking: false
  307. };
  308. self.setOption = function(opt, val)
  309. {
  310. if (val)
  311. self._options[opt] = val;
  312. else
  313. Object.assign(self._options, opt);
  314. };
  315. if (options)
  316. self.setOption(options);
  317.  
  318. self._var = { event: {} };
  319. self.clearEvent = function()
  320. {
  321. self._var.event.detected = [];
  322. self._var.event.notDetected = [];
  323. };
  324. self.clearEvent();
  325.  
  326. self.on = function(detected, fun)
  327. {
  328. self._var.event[detected?'detected':'notDetected'].push(fun);
  329. return self;
  330. };
  331. self.onDetected = function(cb)
  332. {
  333. return self.on(true, cb);
  334. };
  335. self.onNotDetected = function(cb)
  336. {
  337. return self.on(false, cb);
  338. };
  339. self.emitEvent = function()
  340. {
  341. for (let fun of self._var.event.notDetected)
  342. fun();
  343. if (self._options.resetOnEnd)
  344. self.clearEvent();
  345. return self;
  346. };
  347. self._creatBait = () => null;
  348. self._destroyBait = () => null;
  349. self._checkBait = function() {
  350. setTimeout((() => self.emitEvent()), 1);
  351. };
  352. self.check = function() {
  353. self._checkBait();
  354. return true;
  355. };
  356.  
  357. let callback = function()
  358. {
  359. if (self._options.checkOnLoad)
  360. setTimeout(self.check, 1);
  361. };
  362. window.addEventListener('load', callback, false);
  363. };
  364. nt.define(win, 'FuckAdBlock', FuckAdBlock);
  365. nt.define(win, 'fuckAdBlock', new FuckAdBlock({
  366. checkOnLoad: true,
  367. resetOnEnd: true
  368. }));
  369. }
  370.  
  371. // go.onclasrv.com pop-ups/tab-uners
  372. if (!('zfgloadedpopup' in win))
  373. nt.define(win, 'zfgloadedpopup', true);
  374.  
  375. // CoinHive miner stub. Continuous 100% CPU load can easily kill some CPU with overheat.
  376. if (!('CoinHive' in win))
  377. {
  378. if (location.hostname !== 'cnhv.co')
  379. {
  380. // CoinHive stub for cases when it doesn't affect site functionality
  381. let CoinHiveConstructor = function()
  382. {
  383. console.warn('Fake CoinHive miner created.');
  384. this.setThrottle = nt.func(null);
  385. this.start = nt.func(null);
  386. this.on = nt.func(null);
  387. this.getTotalHashes = nt.func(0);
  388. };
  389. let CoinHiveStub = nt.proxy({
  390. Anonymous: CoinHiveConstructor,
  391. User: CoinHiveConstructor,
  392. Token: CoinHiveConstructor,
  393. JobThread: nt.func(null),
  394. IF_EXCLUSIVE_TAB: false
  395. });
  396. nt.define(win, 'CoinHive', CoinHiveStub);
  397. } else {
  398. // CoinHive wrapper to fool sites which expect it to actually work and return results
  399. let CoinHiveObject;
  400. let fishnet = {
  401. apply: (target, thisArg, args) => {
  402. console.log(`miner.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  403. return target.apply(thisArg, args);
  404. }
  405. };
  406. Object.defineProperty(win, 'CoinHive', {
  407. set: function(obj)
  408. {
  409. if ('Token' in obj)
  410. {
  411. console.log('[CoinHive] Token wrapper applied.');
  412. let _Token = obj.Token.bind(obj);
  413. obj.Token = function(siteKey, goal, params)
  414. {
  415. let _goal = goal;
  416. if (goal > 256)
  417. goal = 256;
  418. console.log(`[CoinHive] Original goal: ${_goal}, new smaller goal ${goal}.`);
  419. console.log(`With smaller goals server may return 'invalid_goal' error and stop working.`);
  420. let miner = _Token(siteKey, goal, params);
  421. miner.setThrottle(0.99);
  422. miner.setThrottle = () => null;
  423. let _start = miner.start.bind(miner);
  424. miner.start = function() {
  425. let res = _start(CoinHive.FORCE_EXCLUSIVE_TAB);
  426. return res;
  427. };
  428. let _getTotalHashes = miner.getTotalHashes;
  429. miner.getTotalHashes = function()
  430. {
  431. return Math.trunc(_getTotalHashes.call(this) / goal * _goal);
  432. };
  433. let __emit = miner._emit;
  434. miner._emit = function(state, props)
  435. {
  436. let _self = this;
  437. console.log('[CoinHive] state:', state, props);
  438. if (state === 'job')
  439. setTimeout(() => {
  440. _self.stop();
  441. _self._emit('accepted', { hashes: goal });
  442. }, 1000);
  443. return __emit.apply(_self, arguments);
  444. };
  445. let _on = miner.on.bind(miner);
  446. miner.on = function(type, callback)
  447. {
  448. if (type === 'accepted')
  449. {
  450. console.log('[CoinHive] "accepted" callback wrapper applied.');
  451. let _callback = callback;
  452. callback = function(params)
  453. {
  454. console.log('[CoinHive] "accepted" callback is called, imitating original goal being reached.');
  455. params.hashes = _goal;
  456. return _callback.apply(this, arguments);
  457. };
  458. miner.stop();
  459. }
  460. return _on(type, callback);
  461. };
  462. return miner;
  463. };
  464. }
  465. CoinHiveObject = obj;
  466. },
  467. get: () => CoinHiveObject
  468. });
  469. }
  470. }
  471.  
  472. // Yandex API (ADBTools, Metrika)
  473. let hostname = location.hostname;
  474. if (location.protocol === 'about:' ||
  475. // Thank you, Greasemonkey, now I have to check for this. -_-
  476. hostname.startsWith('google.') || hostname.includes('.google.') ||
  477. // Google likes to define odd global variables like Ya
  478. ((hostname.startsWith('yandex.') || hostname.includes('.yandex.')) &&
  479. /^\/((yand)?search|images)/i.test(location.pathname) &&
  480. !hostname.startsWith('news.')) ||
  481. // Also, Yandex uses their Ya object for a lot of things on their pages and
  482. // wrapping it may cause problems. It's better to skip it in some cases.
  483. hostname.endsWith('github.io') || hostname.endsWith('grimtools.com'))
  484. return;
  485.  
  486. let YaProps = new Set();
  487. function onAdvManager (Ya, rootProp, obj)
  488. {
  489. return new Proxy(obj, {
  490. set: (tgt, prop, val) => {
  491. if (prop === 'AdvManager')
  492. {
  493. console.log(`Ya.${rootProp} = Ya.Context`);
  494. nt.define(Ya, rootProp, Ya.Context);
  495. YaProps.add(rootProp);
  496. }
  497. tgt[prop] = val;
  498. return true;
  499. },
  500. get: (tgt, prop) => tgt[prop]
  501. });
  502. }
  503. let Ya = new Proxy({}, {
  504. set: function(tgt, prop, val)
  505. {
  506. if (val === tgt[prop])
  507. return true;
  508. if (!isNaN(prop))
  509. {
  510. nt.define(Ya, prop, nt.func(null));
  511. YaProps.add(prop);
  512. }
  513. if (YaProps.has(prop))
  514. {
  515. console.log(`Ya.${prop} \u2260`, val);
  516. return true;
  517. }
  518. if (val instanceof Object && prop !== '__inline_params__')
  519. val = onAdvManager(Ya, prop, val);
  520. tgt[prop] = val;
  521. console.log(`Ya.${prop} =`, val);
  522. return true;
  523. },
  524. get: (tgt, prop) => tgt[prop]
  525. });
  526. let callWithParams = function(f)
  527. {
  528. f.call(this, Ya.__inline_params__ || {});
  529. Ya.__inline_params__ = null;
  530. };
  531. nt.define(Ya, 'callWithParams', callWithParams);
  532. nt.define(Ya, 'PerfCounters', nt.proxy({
  533. addCacheEvent: nt.func(null),
  534. getTime: nt.func(null),
  535. sendCacheEvents: nt.func(null),
  536. sendResTiming: nt.func(null),
  537. sendTimeMark: nt.func(null),
  538. __cacheEvents: []
  539. }));
  540. nt.define(Ya, '__isSent', true);
  541. nt.define(Ya, 'confirmUrl', '');
  542. nt.define(Ya, 'Direct', nt.proxy({
  543. insertInto: nt.func(null)
  544. }));
  545. nt.define(Ya, 'mediaCode', nt.proxy({
  546. create: function()
  547. {
  548. if (inIFrame)
  549. {
  550. console.log('Removed body of ad-frame.');
  551. document.documentElement.removeChild(document.body);
  552. }
  553. },
  554. moduleLoad: nt.func(null),
  555. setModule: nt.func(null)
  556. }));
  557. let extra = nt.proxy({
  558. extra: nt.proxy({ match: 0, confirm: '', src: '' }),
  559. id: 0, percent: 100, threshold: 1
  560. });
  561. nt.define(Ya, '_exp', nt.proxy({
  562. id: 0, coin: 0,
  563. choose: nt.func(extra),
  564. get: (prop) => extra.hasOwnProperty(prop) ? extra[prop] : null,
  565. getId: nt.func(0),
  566. defaultVersion: extra,
  567. getExtra: nt.func(extra.extra),
  568. getDefaultExtra: nt.func(extra.extra),
  569. versions: [extra]
  570. }));
  571. nt.define(Ya, 'c', nt.func(null));
  572. nt.define(Ya, 'ADBTools', function(){
  573. ['loadContext', 'testAdbStyle'].map(name => this[name] = nt.func(null));
  574. this.getCurrentState = nt.func(true);
  575. return nt.proxy(this);
  576. });
  577.  
  578. if (!location.hostname.includes('kinopoisk.ru')) {
  579. // kinopoisk uses adfox wrapped in Yandex code to display self-ads
  580. let adfoxCode = {};
  581. [
  582. 'create', 'reload', 'destroy',
  583. 'createAdaptive', 'moduleLoad',
  584. 'createScroll', 'pr'
  585. ].map(name => adfoxCode[name] = nt.func(null, name));
  586. nt.define(Ya, 'adfoxCode', nt.proxy(adfoxCode));
  587. } else {
  588. nt.define(win, 'abExperiments', nt.proxy([]));
  589. }
  590. let AdvManager = function()
  591. {
  592. [
  593. 'renderDirect',
  594. 'getBid', 'releaseBid',
  595. 'getSkipToken',
  596. 'getAdSessionId'
  597. ].map(name => this[name] = nt.func(null, name));
  598. this.render = function(o) {
  599. if (!o.renderTo)
  600. return;
  601. let placeholder = document.getElementById(o.renderTo);
  602. let parent = placeholder.parentNode;
  603. placeholder.style = 'display:none!important';
  604. parent.style = (parent.getAttribute('style')||'') + 'height:auto!important';
  605. // fix for Yandex TV pages
  606. if (location.hostname.startsWith('tv.yandex.'))
  607. {
  608. let sibling = placeholder.previousSibling;
  609. if (sibling && sibling.classList && sibling.classList.contains('tv-spin'))
  610. sibling.style.display = 'none';
  611. }
  612. };
  613. return nt.proxy(this);
  614. };
  615. nt.define(Ya, 'Context', nt.proxy({
  616. __longExperiment: null,
  617. _callbacks: nt.proxy([]),
  618. _asyncModeOn: true,
  619. _init: nt.func(null),
  620. isAllowedRepeatAds: nt.func(null),
  621. AdvManager: new AdvManager()
  622. }));
  623. let Metrika = function()
  624. {
  625. [
  626. 'reachGoal', 'replacePhones',
  627. 'trackLinks', 'userParams',
  628. 'hit', 'params', 'clickmap'
  629. ].map(name => this[name] = nt.func(null, name));
  630. this.id = 0;
  631. return nt.proxy(this);
  632. };
  633. Metrika.counters = () => Ya._metrika.counters;
  634. nt.define(Ya, 'Metrika', Metrika);
  635. let counter = new Ya.Metrika();
  636. nt.define(Ya, '_metrika', nt.proxy({
  637. counter: counter,
  638. counters: [counter],
  639. hitParam: {},
  640. counterNum: 0,
  641. hitId: 0,
  642. v: 1
  643. }));
  644. nt.define(Ya, '_globalMetrikaHitId', 0);
  645. counter = {};
  646. [
  647. 'cpHitDelayed','wHitDelayed',
  648. 'hitDelayed','makeReq',
  649. 'redir','hit','log','cp','w'
  650. ].map(name => counter[name] = nt.func(null, name));
  651. [
  652. 'stringifyParams','_getVars',
  653. 'getUid','getUrl','getHash'
  654. ].map(name => counter[name] = nt.func(''));
  655. nt.define(Ya, 'counter', nt.proxy(counter));
  656. nt.define(Ya, 'jserrors', []);
  657. nt.define(Ya, 'onerror', nt.func());
  658. let Rum = {};
  659. [
  660. '__timeMarks', '_timeMarks', '__deltaMarks', '_deltaMarks',
  661. '__defRes', '_defRes', '__defTimes', '_defTimes',
  662. 'commonVars'
  663. ].map(name => Rum[name] = []);
  664. [
  665. 'sendTimeMark', 'sendResTiming', 'getTime',
  666. 'sendRaf', 'time', 'timeEnd', 'mark', 'send'
  667. ].map(name => Rum[name] = nt.func(null, name));
  668. Rum.getVarsList = nt.func([], 'getVarsList');
  669. Rum.isVisibilityChanged = nt.func(false, 'isVisibilityChanged');
  670. nt.define(Ya, 'Rum', nt.proxy(Rum));
  671. for (let prop in Ya)
  672. YaProps.add(prop);
  673. nt.define(win, 'Ya', Ya);
  674. // Yandex.Metrika callbacks
  675. let yandex_metrika_callbacks = [];
  676. document.addEventListener(
  677. 'DOMContentLoaded',
  678. (e) => {
  679. yandex_metrika_callbacks.forEach((f) => f && f.call(window));
  680. yandex_metrika_callbacks.length = 0;
  681. yandex_metrika_callbacks.push = (f) => setTimeout(f, 0);
  682. },
  683. false
  684. );
  685. nt.define(win, 'yandex_metrika_callbacks', yandex_metrika_callbacks);
  686. }, nullTools
  687. );
  688.  
  689. // Creates and return protected style (unless protection is manually disabled).
  690. // Protected style will re-add itself on removal and remaind enabled on attempt to disable it.
  691. function createStyle(rules, props, skip_protect)
  692. {
  693. props = props || {};
  694. props.type = 'text/css';
  695.  
  696. function _protect(style)
  697. {
  698. if (skip_protect)
  699. return;
  700.  
  701. Object.defineProperty(style, 'sheet', {
  702. value: null,
  703. enumerable: true
  704. });
  705. Object.defineProperty(style, 'disabled', {
  706. get: () => true, //pretend to be disabled
  707. set: () => undefined,
  708. enumerable: true
  709. });
  710. (new MutationObserver(
  711. (ms) => _removeChild(ms[0].target)
  712. )).observe(style, { childList: true });
  713. }
  714.  
  715.  
  716. function _create()
  717. {
  718. let style = _appendChild(_createElement('style'));
  719. Object.assign(style, props);
  720.  
  721. function insertRules(rule)
  722. {
  723. if (rule.forEach)
  724. rule.forEach(insertRules);
  725. else try {
  726. style.sheet.insertRule(rule, 0);
  727. } catch (e) {
  728. console.error(e);
  729. }
  730. }
  731.  
  732. insertRules(rules);
  733. _protect(style);
  734.  
  735. return style;
  736. }
  737.  
  738. let style = _create();
  739. if (skip_protect)
  740. return style;
  741.  
  742. function resolveInANewContext(resolve)
  743. {
  744. setTimeout(
  745. (resolve) => resolve(_create()),
  746. 0, resolve
  747. );
  748. }
  749.  
  750. (new MutationObserver(
  751. function(ms)
  752. {
  753. let m, node;
  754. for (m of ms) for (node of m.removedNodes)
  755. if (node === style)
  756. (new Promise(resolveInANewContext))
  757. .then((st) => (style = st));
  758. }
  759. )).observe(_de, { childList: true });
  760.  
  761. return style;
  762. }
  763.  
  764. // https://greasyfork.org/scripts/19144-websuckit/
  765. function useWSI()
  766. {
  767. // check does browser support Proxy and WebSocket
  768. if (typeof Proxy !== 'function' ||
  769. typeof WebSocket !== 'function')
  770. return;
  771.  
  772. function getWrappedCode()
  773. {
  774. let text = getWrappedCode.toString() + WSI.toString();
  775. return `(function(){"use strict";${(
  776. text.replace(/\/\/[^\r\n]*/g,'').replace(/[\s\r\n]+/g,' ')
  777. )}(new WSI(self||window)).init();})();\n`;
  778. }
  779.  
  780. function WSI(win, safeWin)
  781. {
  782. safeWin = safeWin || win;
  783. let masks = [], filter;
  784. for (filter of [// blacklist
  785. '||185.87.50.147^',
  786. '||10root25.website^', '||24video.xxx^',
  787. '||adlabs.ru^', '||adspayformymortgage.win^', '||aviabay.ru^',
  788. '||bgrndi.com^', '||brokeloy.com^',
  789. '||cnamerutor.ru^',
  790. '||docfilms.info^', '||dreadfula.ru^',
  791. '||et-code.ru^', '||etcodes.com^',
  792. '||franecki.net^', '||film-doma.ru^',
  793. '||free-torrent.org^', '||free-torrent.pw^',
  794. '||free-torrents.org^', '||free-torrents.pw^',
  795. '||game-torrent.info^', '||gocdn.ru^',
  796. '||hdkinoshka.com^', '||hghit.com^', '||hindcine.net^',
  797. '||joyreactor.cc^', '||pornreactor.cc^', '||reactor.cc^',
  798. '||kiev.ua^', '||kinotochka.net^',
  799. '||kinott.com^', '||kinott.ru^', '||kuveres.com^',
  800. '||lepubs.com^', '||luxadv.com^', '||luxup.ru^', '||luxupcdna.com^',
  801. '||mail.ru^', '||marketgid.com^', '||mixadvert.com^', '||mxtads.com^',
  802. '||nickhel.com^',
  803. '||oconner.biz^', '||oconner.link^', '||octoclick.net^', '||octozoon.org^',
  804. '||pkpojhc.com^',
  805. '||psma01.com^', '||psma02.com^', '||psma03.com^',
  806. '||recreativ.ru^', '||redtram.com^', '||regpole.com^',
  807. '||rootmedia.ws^', '||ruttwind.com^', '||rutvind.com^',
  808. '||skidl.ru^',
  809. '||torvind.com^', '||traffic-media.co^', '||trafmag.com^', '||ttarget.ru^',
  810. '||webadvert-gid.ru^', '||webadvertgid.ru^',
  811. '||xxuhter.ru^',
  812. '||yuiout.online^',
  813. '||zoom-film.ru^'])
  814. masks.push(new RegExp(
  815. filter.replace(/([\\\/\[\].*+?(){}$])/g, '\\$1')
  816. .replace(/\^(?!$)/g,'\\.?[^\\w%._-]')
  817. .replace(/\^$/,'\\.?([^\\w%._-]|$)')
  818. .replace(/^\|\|/,'^(ws|http)s?:\\/+([^\/.]+\\.)*'),
  819. 'i'));
  820.  
  821. function isBlocked(url) {
  822. for (let mask of masks)
  823. if (mask.test(url))
  824. return true;
  825. return false;
  826. }
  827.  
  828. function wrapWebSocket(wsParent)
  829. {
  830. let _WebSocket = wsParent.WebSocket;
  831. // getter for properties of fake WS, returns fake functions
  832. // if there are functions with such name in the real WS and
  833. // also returns constants from real WS
  834. function wsGetter(target, name)
  835. {
  836. try {
  837. if (typeof _WebSocket.prototype[name] === 'function')
  838. {
  839. if (name === 'close' || name === 'send') // send also closes connection
  840. target.readyState = _WebSocket.CLOSED;
  841. return (
  842. function fake() {
  843. console.warn(`[WSI] Invoked function "${name}"`);
  844. return;
  845. }
  846. );
  847. }
  848. if (typeof _WebSocket.prototype[name] === 'number')
  849. return _WebSocket[name];
  850. } catch(ignore) {}
  851. return target[name];
  852. }
  853. // Wrap WS object
  854. wsParent.WebSocket = new Proxy(_WebSocket, {
  855. construct: function (target, args)
  856. {
  857. let url = args[0];
  858. console.log(`[WSI] Opening socket on ${url}\u2026`);
  859. if (isBlocked(url))
  860. {
  861. console.log("[WSI] Blocked.");
  862. return new Proxy({
  863. url: url,
  864. readyState: _WebSocket.OPEN
  865. }, {
  866. get: wsGetter,
  867. set: () => true
  868. });
  869. }
  870. return Reflect.construct(target, args);
  871. }
  872. });
  873. }
  874.  
  875. function WorkerWrapper()
  876. {
  877. let realWorker = win.Worker;
  878. win.Worker = function Worker() {
  879. let isBlobURL = /^blob:/i,
  880. resourceURI = arguments[0],
  881. deepLogMode = false,
  882. _callbacks = new WeakMap(),
  883. _worker = null,
  884. _onevs = { names: ['onmessage', 'onerror'] },
  885. _actions = [],
  886. _self = this;
  887.  
  888. function log()
  889. {
  890. if (deepLogMode)
  891. console.log.apply(_self, arguments);
  892. }
  893.  
  894. function callbackWrapper(func)
  895. {
  896. if (typeof func !== 'function')
  897. return undefined;
  898.  
  899. return function callback()
  900. {
  901. return func.apply(_self, arguments);
  902. };
  903. }
  904.  
  905. function updateWorker()
  906. {
  907. for (let [action, name, args] of _actions) {
  908. log(_worker, action, name, args);
  909. if (action === 'set')
  910. _worker[name] = callbackWrapper(args);
  911. if (action === 'call')
  912. _worker[name].apply(_worker, args);
  913. }
  914. _actions.length = 0;
  915. log('Applied buffered actions.');
  916. }
  917.  
  918. for (let prop of _onevs.names)
  919. Object.defineProperty(_self, prop, {
  920. set: function(...args) {
  921. let val = args[0];
  922. _onevs[prop] = val;
  923. if (_worker)
  924. _worker[prop] = callbackWrapper(val);
  925. else {
  926. _actions.push(['set', prop, val]);
  927. log('Stored into buffer:', args);
  928. }
  929. },
  930. get: () => _onevs[prop],
  931. enumerable: true
  932. });
  933.  
  934. _self.postMessage = function(...args)
  935. {
  936. if (_worker)
  937. _worker.postMessage.apply(_worker, args);
  938. else {
  939. _actions.push(['call', 'postMessage', args]);
  940. log('Stored into buffer:', args);
  941. }
  942. };
  943. _self.terminate = function(...args)
  944. {
  945. if (_worker)
  946. _worker.terminate();
  947. else {
  948. _actions.push(['call','terminate', args]);
  949. log('Stored into buffer:', args);
  950. }
  951. };
  952. _self.addEventListener = function(...args)
  953. {
  954. let [event, callback, other] = args;
  955. if (typeof callback !== 'function')
  956. return;
  957.  
  958. if (!_callbacks.has(callback))
  959. _callbacks.set(callback, callbackWrapper(callback));
  960.  
  961. args[1] = _callbacks.get(callback);
  962. if (_worker)
  963. _worker.addEventListener.apply(_worker, args);
  964. else {
  965. _actions.push(['call', 'addEventListener', args]);
  966. log('Stored into buffer:', args);
  967. }
  968. };
  969. _self.removeEventListener = function(...args)
  970. {
  971. let [event, callback, other] = args;
  972. if (typeof callback !== 'function' || !_callbacks.has(callback))
  973. return;
  974.  
  975. args[1] = _callbacks.get(callback);
  976. _callbacks.delete(callback);
  977. if (_worker)
  978. _worker.removeEventListener.apply(_worker, args);
  979. else {
  980. _actions.push(['call', 'removeEventListener', args]);
  981. log('Stored into buffer:', args);
  982. }
  983. };
  984.  
  985. if (!isBlobURL.test(resourceURI))
  986. {
  987. _worker = new realWorker(resourceURI);
  988. return; // not a blob, no need to wrap
  989. }
  990.  
  991. (new Promise(
  992. function(resolve, reject)
  993. {
  994. let xhr = new XMLHttpRequest();
  995. xhr.responseType = 'blob';
  996. try {
  997. xhr.open('GET', resourceURI, true);
  998. } catch(e) {
  999. return reject(e);
  1000. }
  1001. if (xhr.readyState !== XMLHttpRequest.OPENED) {
  1002. // connection wasn't opened, unable to continue wrapping procedure
  1003. return reject(xhr.readyState);
  1004. }
  1005. xhr.onload = function(e)
  1006. {
  1007. if (e.target.status === 200)
  1008. {
  1009. let reader = new FileReader();
  1010. reader.addEventListener(
  1011. 'loadend', function(e)
  1012. {
  1013. resolve(
  1014. new realWorker(URL.createObjectURL(
  1015. new Blob([getWrappedCode() + e.target.result])
  1016. ))
  1017. );
  1018. }, false
  1019. );
  1020. reader.readAsText(e.target.response);
  1021. } else {
  1022. return reject(e);
  1023. }
  1024. };
  1025. xhr.onerror = (e) => reject(e);
  1026. xhr.send();
  1027. }
  1028. )).then(
  1029. function(val)
  1030. {
  1031. _worker = val;
  1032. updateWorker();
  1033. }
  1034. ).catch(
  1035. function(e)
  1036. {
  1037. // connection were blocked by CSP or something else triggered error event on xhr object
  1038. // unable to proceed with wrapper, return object as-is
  1039. _worker = new realWorker(resourceURI);
  1040. updateWorker();
  1041. }
  1042. );
  1043.  
  1044. if (deepLogMode)
  1045. {
  1046. return new Proxy(_self, {
  1047. get: function(target, prop) {
  1048. console.log(`Get Worker.${prop}`);
  1049. return target[prop];
  1050. },
  1051. set: function(target, prop, val) {
  1052. console.log(`Set Worker.${prop} = ${val}`);
  1053. target[prop] = val;
  1054. return true;
  1055. }
  1056. });
  1057. }
  1058. }.bind(safeWin);
  1059.  
  1060. realWorker.prototype.constructor = win.Worker;
  1061. win.Worker.prototype = realWorker.prototype;
  1062. }
  1063.  
  1064. function CreateElementWrapper()
  1065. {
  1066. let key = `_${Math.random().toString(36).substr(2)}`,
  1067. _createElement = Document.prototype.createElement,
  1068. _addEventListener = Element.prototype.addEventListener,
  1069. isDataURL = /^data:/i,
  1070. isBlobURL = /^blob:/i;
  1071.  
  1072. // IFrame SRC get/set wrapper
  1073. let ifGetSet = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
  1074. if (ifGetSet)
  1075. {
  1076. let code = encodeURIComponent(`<script>${getWrappedCode()}</script>\n`),
  1077. dataSrc = new WeakMap(),
  1078. _ifSet = ifGetSet.set,
  1079. _ifGet = ifGetSet.get;
  1080. ifGetSet.set = function(val)
  1081. {
  1082. if (this[key] && val === dataSrc.get(this))
  1083. { // if already processed data URL then do nothing
  1084. delete this[key];
  1085. return null;
  1086. }
  1087. let isData = isDataURL.test(val);
  1088. if (isData && val.indexOf(code) < 0)
  1089. {
  1090. dataSrc.set(this, val);
  1091. val = val.replace(',', `,${code}`);
  1092. }
  1093. if (!isData && dataSrc.get(this))
  1094. dataSrc.delete(this);
  1095. return _ifSet.call(this, val);
  1096. };
  1097. ifGetSet.get = function()
  1098. {
  1099. return dataSrc.get(this) || _ifGet.call(this);
  1100. };
  1101. Object.defineProperty(HTMLIFrameElement.prototype, 'src', ifGetSet);
  1102. }
  1103.  
  1104. function frameSetWSWrapper(e)
  1105. {
  1106. let frm = e.target;
  1107. try {
  1108. if (!frm.src || isBlobURL.test(frm.src))
  1109. wrapWebSocket(frm.contentWindow);
  1110. } catch (ignore) {}
  1111. }
  1112.  
  1113. let scriptMap = new WeakMap();
  1114. scriptMap.isBlocked = isBlocked;
  1115. let onErrorWrapper = {
  1116. set: function(val)
  1117. {
  1118. if (scriptMap.has(this))
  1119. {
  1120. this.removeEventListener('error', scriptMap.get(this).wrp, false);
  1121. scriptMap.delete(this);
  1122. }
  1123. if (!val || typeof val !== 'function')
  1124. return val;
  1125.  
  1126. scriptMap.set(this, {
  1127. org: val,
  1128. wrp: function(...args)
  1129. {
  1130. if (scriptMap.isBlocked(this.src))
  1131. console.log('[WSI] Blocked "onerror" callback from', this.src);
  1132. else
  1133. scriptMap.get(this).org.apply(this, args);
  1134. }
  1135. });
  1136. this.addEventListener('error', scriptMap.get(this).wrp, false);
  1137. },
  1138. get: function()
  1139. {
  1140. return scriptMap.has(this) ? scriptMap.get(this).org : null;
  1141. },
  1142. enumerable: true
  1143. };
  1144. Document.prototype.createElement = function createElement(...args) {
  1145. let el = _createElement.apply(this, args);
  1146.  
  1147. if (el.tagName === 'IFRAME')
  1148. _addEventListener.call(el, 'load', frameSetWSWrapper, false);
  1149. if (el.tagName === 'SCRIPT')
  1150. Object.defineProperty(el, 'onerror', onErrorWrapper);
  1151.  
  1152. return el;
  1153. };
  1154.  
  1155. document.addEventListener(
  1156. 'DOMContentLoaded', function()
  1157. {
  1158. for (let ifr of document.querySelectorAll('IFRAME'))
  1159. {
  1160. if (isDataURL.test(ifr.src))
  1161. {
  1162. ifr[key] = true;
  1163. ifr.src = ifr.src; // call setter and let it do the job
  1164. }
  1165. _addEventListener.call(ifr, 'load', frameSetWSWrapper, false);
  1166. }
  1167. }, false
  1168. );
  1169. }
  1170.  
  1171. this.init = function()
  1172. {
  1173. wrapWebSocket(win);
  1174. if (!(/firefox/i.test(navigator.userAgent))) // skip WorkerWrapper in Firefox
  1175. (new Promise(
  1176. function(resolve, reject)
  1177. { // test is it possible to run inline scripts
  1178. if (self.constructor.name.indexOf('Worker') > -1)
  1179. return resolve(); // running within a Worker
  1180. let onerr = window.onerror,
  1181. onscr = (e) => resolve();
  1182. // for some reason addEventListener on 'error' doesn't catch this error
  1183. window.onerror = (e) => reject(e);
  1184. window.addEventListener('inlineSuccess', onscr, false);
  1185. let scr = document.createElement('script');
  1186. scr.textContent = "window.dispatchEvent(new Event('inlineSuccess'));";
  1187. document.documentElement.appendChild(scr);
  1188. document.documentElement.removeChild(scr);
  1189. window.removeEventListener('inlineSuccess', onscr, false);
  1190. window.onerror = onerr;
  1191. }
  1192. )).then(
  1193. (e) => WorkerWrapper()
  1194. ).catch(
  1195. (e) => console.log('[WSI] Unable to create inline script. Skipping Worker wrapper to avoid further issues.', e)
  1196. );
  1197. if (typeof document !== 'undefined')
  1198. CreateElementWrapper();
  1199. };
  1200. }
  1201.  
  1202. if (isFirefox)
  1203. {
  1204. let script = _createElement('script');
  1205. script.textContent = getWrappedCode();
  1206. _appendChild(script);
  1207. _removeChild(script);
  1208. return; //we don't want to call functions on page from here in Fx, so exit
  1209. }
  1210.  
  1211. (new WSI((unsafeWindow||self||window),(self||window))).init();
  1212. }
  1213.  
  1214. if (!isFirefox)
  1215. { // scripts for non-Firefox browsers
  1216. // https://greasyfork.org/scripts/14720-it-s-not-important
  1217. {
  1218. let imptt = /((display|(margin|padding)(-top|-bottom)?)\s*:[^;!]*)!\s*important/ig,
  1219. ret_b = (a,b) => b,
  1220. _toLowerCase = String.prototype.toLowerCase,
  1221. protectedNodes = new WeakSet(),
  1222. log = false;
  1223.  
  1224. let logger = function()
  1225. {
  1226. if (log)
  1227. console.log('Some page elements became a bit less important.');
  1228. log = false;
  1229. };
  1230.  
  1231. let unimportanter = function(node)
  1232. {
  1233. let style = (node.nodeType === Node.ELEMENT_NODE) ?
  1234. _getAttribute.call(node, 'style') : null;
  1235.  
  1236. if (!style || !imptt.test(style) || node.style.display === 'none' ||
  1237. (node.src && node.src.slice(0,17) === 'chrome-extension:')) // Web of Trust IFRAME and similar
  1238. return false; // get out if we have nothing to do here
  1239.  
  1240. protectedNodes.add(node);
  1241. _setAttribute.call(node, 'style',
  1242. style.replace(imptt, ret_b));
  1243. log = true;
  1244. };
  1245.  
  1246. (new MutationObserver(
  1247. function(mutations)
  1248. {
  1249. setTimeout(
  1250. function(ms)
  1251. {
  1252. let m, node;
  1253. for (m of ms) for (node of m.addedNodes)
  1254. unimportanter(node);
  1255. logger();
  1256. }, 0, mutations
  1257. );
  1258. }
  1259. )).observe(document, {
  1260. childList : true,
  1261. subtree : true
  1262. });
  1263.  
  1264. Element.prototype.setAttribute = function setAttribute(name, value)
  1265. {
  1266. "[native code]";
  1267. let replaced = value;
  1268. if (_toLowerCase.call(name) === 'style' && protectedNodes.has(this))
  1269. replaced = value.replace(imptt, ret_b);
  1270. log = (replaced !== value);
  1271. logger();
  1272. return _setAttribute.call(this, name, replaced);
  1273. };
  1274.  
  1275. win.addEventListener (
  1276. 'load', function()
  1277. {
  1278. for (let imp of document.querySelectorAll('[style*="!"]'))
  1279. unimportanter(imp);
  1280. logger();
  1281. }, false
  1282. );
  1283. }
  1284.  
  1285. // Naive ABP Style protector
  1286. {
  1287. let _querySelector = Document.prototype.querySelector.bind(document);
  1288. let _removeChild = Node.prototype.removeChild;
  1289. let _appendChild = Node.prototype.appendChild;
  1290. let createShadow = () => _createElement('shadow');
  1291. // Prevent adding fake content entry point
  1292. Node.prototype.appendChild = function(child)
  1293. {
  1294. if (this instanceof ShadowRoot &&
  1295. child instanceof HTMLContentElement)
  1296. return _appendChild.call(this, createShadow());
  1297. return _appendChild.apply(this, arguments);
  1298. };
  1299. {
  1300. let _shadowSelector = ShadowRoot.prototype.querySelector;
  1301. let _innerHTML = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'innerHTML');
  1302. let _parentNode = Object.getOwnPropertyDescriptor(Node.prototype, 'parentNode');
  1303. if (_innerHTML && _parentNode)
  1304. {
  1305. let _set = _innerHTML.set;
  1306. let _getParent = _parentNode.get;
  1307. _innerHTML.configurable = false;
  1308. _innerHTML.set = function()
  1309. {
  1310. _set.apply(this, arguments);
  1311. let content = _shadowSelector.call(this, 'content');
  1312. if (content)
  1313. {
  1314. let parent = _getParent.call(content);
  1315. _removeChild.call(parent, content);
  1316. _appendChild.call(parent, createShadow());
  1317. }
  1318. };
  1319. }
  1320. Object.defineProperty(ShadowRoot.prototype, 'innerHTML', _innerHTML);
  1321. }
  1322. // Locate and apply extra protection to a style on top of what ABP does
  1323. let style;
  1324. (new Promise(
  1325. function(resolve, reject)
  1326. {
  1327. let getStyle = () => _querySelector('::shadow style');
  1328. style = getStyle();
  1329. if (style)
  1330. return resolve(style);
  1331. let intv = setInterval(
  1332. function()
  1333. {
  1334. style = getStyle();
  1335. if (!style)
  1336. return;
  1337. intv = clearInterval(intv);
  1338. return resolve(style);
  1339. }, 0
  1340. );
  1341. document.addEventListener(
  1342. 'DOMContentLoaded',
  1343. function()
  1344. {
  1345. if (intv)
  1346. clearInterval(intv);
  1347. style = getStyle();
  1348. return style ? resolve(style) : reject();
  1349. },
  1350. false
  1351. );
  1352. }
  1353. )).then(
  1354. function(style)
  1355. {
  1356. let emptyArr = [],
  1357. nullStr = {
  1358. get: () => '',
  1359. set: () => undefined
  1360. };
  1361. let shadow = style.parentNode;
  1362. Object.defineProperties(shadow, {
  1363. childElementCount: { value: 0 },
  1364. styleSheets: { value: emptyArr },
  1365. firstChild: { value: null },
  1366. firstElementChild: { value: null },
  1367. lastChild: { value: null },
  1368. lastElementChild: { value: null },
  1369. childNodes: { value: emptyArr },
  1370. children: { value: emptyArr },
  1371. innerHTML: { value: nullStr },
  1372. });
  1373. Object.defineProperties(style, {
  1374. innerHTML: { value: nullStr },
  1375. textContent: { value: nullStr },
  1376. ownerDocument: { value: null },
  1377. parentNode: {value: null },
  1378. previousElementSibling: { value: null },
  1379. previousSibling: { value: null },
  1380. disabled: { get: () => true, set: x => null }
  1381. });
  1382. Object.defineProperties(style.sheet, {
  1383. deleteRule: { value: () => null },
  1384. disabled: { get: () => true, set: x => null },
  1385. cssRules: { value: emptyArr },
  1386. rules: { value: emptyArr }
  1387. });
  1388. }
  1389. ).catch(()=>null);
  1390. Node.prototype.removeChild = function(child)
  1391. {
  1392. if (child === style)
  1393. return;
  1394. return _removeChild.apply(this, arguments);
  1395. };
  1396. }
  1397. }
  1398. if (/^https?:\/\/(mail\.yandex\.|music\.yandex\.|news\.yandex\.|(www\.)?yandex\.[^\/]+\/(yand)?search[\/?])/i.test(win.location.href) ||
  1399. /^https?:\/\/tv\.yandex\./i.test(win.location.href))
  1400. {
  1401. // https://greasyfork.org/en/scripts/809-no-yandex-ads
  1402. let yadWord = /Яндекс.Директ/i,
  1403. adWords = /Реклама|Ad/i;
  1404. let _querySelector = document.querySelector.bind(document),
  1405. _querySelectorAll = document.querySelectorAll.bind(document),
  1406. _getAttribute = Element.prototype.getAttribute,
  1407. _setAttribute = Element.prototype.setAttribute;
  1408. // Function to attach an observer to monitor dynamic changes on the page
  1409. let pageUpdateObserver = (func, obj, params) => {
  1410. if (obj)
  1411. (new MutationObserver(func))
  1412. .observe(obj, (params || { childList:true, subtree:true }));
  1413. };
  1414. // Short name for parentNode.removeChild
  1415. let remove = (node) => {
  1416. if (!node || !node.parentNode)
  1417. return false;
  1418. console.log('Removed node.');
  1419. node.parentNode.removeChild(node);
  1420. };
  1421. // Yandex search ads in Google Chrome
  1422. if ('attachShadow' in Element.prototype)
  1423. {
  1424. let _attachShadow = Element.prototype.attachShadow;
  1425. Element.prototype.attachShadow = function()
  1426. {
  1427. let node = this,
  1428. root = _attachShadow.apply(node, arguments);
  1429. pageUpdateObserver(
  1430. (ms) => {
  1431. for (let m of ms) if (m.addedNodes.length)
  1432. if (adWords.test(root.textContent))
  1433. remove(node.closest('.serp-item'));
  1434. }, root
  1435. );
  1436. return root;
  1437. };
  1438. }
  1439. // prevent/defuse adblock detector
  1440. setInterval(()=>{
  1441. localStorage.ic = '';
  1442. localStorage._mt__data = '';
  1443. },100);
  1444. let _doc_proto = ('cookie' in Document.prototype) ? Document.prototype : Object.getPrototypeOf(document);
  1445. let _cookie = Object.getOwnPropertyDescriptor(_doc_proto, 'cookie');
  1446. if (_cookie)
  1447. {
  1448. let _set_cookie = Function.prototype.call.bind(_cookie.set);
  1449. _cookie.set = function(value)
  1450. {
  1451. if (/^(mda=|yp=|ys=|yabs-|__)/.test(value))
  1452. {
  1453. // remove value, set expired
  1454. if (!value.startsWith('yp=')) {
  1455. value = value.replace(/^([^=]+=)[^;]+/,'$1').replace(/(expires=)[\w\s\d,]+/,'$1Thu, 01 Jan 1970 00');
  1456. console.log('expire cookie', value.match(/^[^=]+/)[0]);
  1457. } else {
  1458. let parts = value.split(';');
  1459. let values = parts[0].split('#').filter(part => /\.sp\./.test(part));
  1460. if (values.length)
  1461. values[0] = values[0].replace(/^yp=/, '');
  1462. parts[0] = `yp=${values.join('#')}`;
  1463. value = parts.join(';');
  1464. console.log(`set cookie ${parts[0]}`);
  1465. }
  1466. //return null;
  1467. }
  1468. return _set_cookie(this, value);
  1469. };
  1470. Object.defineProperty(_doc_proto, 'cookie', _cookie);
  1471. }
  1472. // other ads
  1473. document.addEventListener(
  1474. 'DOMContentLoaded', function()
  1475. {
  1476. { // Generic ads removal and fixes
  1477. let node = _querySelector('.serp-header');
  1478. if (node)
  1479. node.style.marginTop = '0';
  1480. for (node of _querySelectorAll(
  1481. '.serp-adv__head + .serp-item,'+
  1482. '#adbanner,'+
  1483. '.serp-adv,'+
  1484. '.b-spec-adv,'+
  1485. 'div[class*="serp-adv__"]:not(.serp-adv__found):not(.serp-adv__displayed)'
  1486. )) remove(node);
  1487. }
  1488. // Search ads
  1489. function removeSearchAds()
  1490. {
  1491. for (let node of _querySelectorAll('.serp-item'))
  1492. if (_getAttribute.call(node, 'role') === 'complementary' ||
  1493. adWords.test((node.querySelector('.label')||{}).textContent))
  1494. remove(node);
  1495. }
  1496. // News ads
  1497. function removeNewsAds()
  1498. {
  1499. let node, block, item, items, mask, classes,
  1500. masks = [
  1501. { class: '.ads__wrapper', regex: /[^,]*?,[^,]*?\.ads__wrapper/ },
  1502. { class: '.ads__pool', regex: /[^,]*?,[^,]*?\.ads__pool/ }
  1503. ];
  1504. for (node of _querySelectorAll('style[nonce]'))
  1505. {
  1506. classes = node.innerText.replace(/\{[^}]+\}+/ig, '|').split('|');
  1507. for (block of classes) for (mask of masks)
  1508. if (block.includes(mask.class))
  1509. {
  1510. block = block.match(mask.regex)[0];
  1511. items = _querySelectorAll(block);
  1512. for (item of items)
  1513. remove(items[0]);
  1514. }
  1515. }
  1516. }
  1517. // Music ads
  1518. function removeMusicAds()
  1519. {
  1520. for (let node of _querySelectorAll('.ads-block'))
  1521. remove(node);
  1522. }
  1523. // Mail ads
  1524. function removeMailAds()
  1525. {
  1526. let slice = Array.prototype.slice,
  1527. nodes = slice.call(_querySelectorAll('.ns-view-folders')),
  1528. node, len, cls;
  1529.  
  1530. for (node of nodes)
  1531. if (!len || len > node.classList.length)
  1532. len = node.classList.length;
  1533.  
  1534. node = nodes.pop();
  1535. while (node)
  1536. {
  1537. if (node.classList.length > len)
  1538. for (cls of slice.call(node.classList))
  1539. if (cls.indexOf('-') === -1)
  1540. {
  1541. remove(node);
  1542. break;
  1543. }
  1544. node = nodes.pop();
  1545. }
  1546. }
  1547. // News fixes
  1548. function removePageAdsClass()
  1549. {
  1550. if (document.body.classList.contains("b-page_ads_yes"))
  1551. {
  1552. document.body.classList.remove("b-page_ads_yes");
  1553. console.log('Page ads class removed.');
  1554. }
  1555. }
  1556. // TV fixes
  1557. function removeTVAds()
  1558. {
  1559. for (let node of _querySelectorAll('div[class^="_"][data-reactid] > div'))
  1560. if (yadWord.test(node.textContent) || node.querySelector('iframe:not([src])'))
  1561. {
  1562. if (node.offsetWidth)
  1563. {
  1564. let pad = document.createElement('div');
  1565. _setAttribute.call(pad, 'style', `width:${node.offsetWidth}px`);
  1566. node.parentNode.appendChild(pad);
  1567. }
  1568. remove(node);
  1569. }
  1570. }
  1571.  
  1572. if (location.hostname.startsWith('mail.')) {
  1573. pageUpdateObserver(
  1574. function(ms, o)
  1575. {
  1576. let aside = _querySelector('.mail-Layout-Aside');
  1577. if (aside) {
  1578. o.disconnect();
  1579. pageUpdateObserver(removeMailAds, aside);
  1580. }
  1581. }, document.body
  1582. );
  1583. removeMailAds();
  1584. } else if (location.hostname.startsWith('music.')) {
  1585. pageUpdateObserver(removeMusicAds, _querySelector('.sidebar'));
  1586. removeMusicAds();
  1587. } else if (location.hostname.startsWith('news.')) {
  1588. pageUpdateObserver(removeNewsAds, document.body);
  1589. pageUpdateObserver(removePageAdsClass, document.body, { attributes:true, attributesFilter:['class'] });
  1590. removeNewsAds();
  1591. removePageAdsClass();
  1592. } else if (location.hostname.startsWith('tv.')) {
  1593. pageUpdateObserver(removeTVAds, document.body);
  1594. removeTVAds();
  1595. } else {
  1596. pageUpdateObserver(removeSearchAds, _querySelector('.main__content'));
  1597. removeSearchAds();
  1598. }
  1599. }
  1600. );
  1601. }
  1602.  
  1603. // Yandex Link Tracking
  1604. if (/^https?:\/\/([^.]+\.)*yandex\.[^\/]+/i.test(win.location.href))
  1605. {
  1606. // remove banner on the start page
  1607. scriptLander(() => {
  1608. let nt = new nullTools({log: false, trace: true});
  1609. let AwapsJsonAPI_Json_prototype = {};
  1610. [
  1611. 'setID', 'addImageContent',
  1612. 'sendCounts', 'expand'
  1613. ].map(name => AwapsJsonAPI_Json_prototype[name] = nt.proxy(nt.func(null, name)));
  1614. AwapsJsonAPI_Json_prototype.checkBannerVisibility = nt.proxy(nt.func(false, 'checkBannerVisibility'));
  1615. AwapsJsonAPI_Json_prototype.addIframeContent = nt.proxy(function(...args) {
  1616. try {
  1617. let frame = args[1][0].parentNode;
  1618. frame.parentNode.removeChild(frame);
  1619. console.log(`Removed banner placeholder.`);
  1620. } catch(ignore) {
  1621. console.log(`Can't locate frame object to remove.`);
  1622. }
  1623. });
  1624. AwapsJsonAPI_Json_prototype.getHTML = nt.proxy(nt.func('', 'getHTML'));
  1625. let AwapsJsonAPI_Json = nt.proxy({ prototype: nt.proxy(AwapsJsonAPI_Json_prototype) });
  1626. if ('AwapsJsonAPI' in win) {
  1627. console.log('Oops! AwapsJsonAPI already defined.');
  1628. win.AwapsJsonAPI.Json = AwapsJsonAPI_Json;
  1629. } else {
  1630. nt.define(win, 'AwapsJsonAPI', nt.proxy({
  1631. Json: AwapsJsonAPI_Json
  1632. }));
  1633. }
  1634.  
  1635. let home = win.home || {};
  1636. let parseExport = x => {
  1637. if (!x)
  1638. return x;
  1639. // remove banner placeholder
  1640. if (x.banner && x.banner.cls) {
  1641. let banners = document.querySelectorAll('.' + x.banner.cls.banner__parent);
  1642. for (let banner of banners) {
  1643. _setAttribute.call(banner, 'style', 'display:none!important');
  1644. console.log('Hid banner placeholder.');
  1645. }
  1646. }
  1647.  
  1648. // remove banner data and some other stuff
  1649. delete x.banner;
  1650. delete x.consistency;
  1651. delete x['i-bannerid'];
  1652. delete x['i-counter'];
  1653. delete x['ga-counter'];
  1654. delete x['promo-curtain'];
  1655.  
  1656. return x;
  1657. };
  1658. let home_export = parseExport(home.export);
  1659. Object.defineProperty(home, 'export', {
  1660. get: x => home_export,
  1661. set: x => {
  1662. home_export = parseExport(x);
  1663. }
  1664. });
  1665. nt.define(win, 'home', home);
  1666. }, nullTools);
  1667.  
  1668. if ('attachShadow' in Element.prototype) {
  1669. let fakeRoot = () => ({
  1670. firstChild: null,
  1671. appendChild: ()=>null,
  1672. querySelector: ()=>null,
  1673. querySelectorAll: ()=>null
  1674. });
  1675. Element.prototype.createShadowRoot = fakeRoot;
  1676. let shadows = new WeakMap();
  1677. let _attachShadow = Object.getOwnPropertyDescriptor(Element.prototype, 'attachShadow');
  1678. let _call_attachShadow = _attachShadow.value;
  1679. _attachShadow.value = function() {
  1680. return shadows.set(this, fakeRoot()).get(this);
  1681. };
  1682. Object.defineProperty(Element.prototype, 'attachShadow', _attachShadow);
  1683. let _shadowRoot = Object.getOwnPropertyDescriptor(Element.prototype, 'shadowRoot');
  1684. _shadowRoot.set = () => null;
  1685. _shadowRoot.get = function() {
  1686. return shadows.has(this) ? shadows.get(this) : void 0;
  1687. };
  1688. Object.defineProperty(Element.prototype, 'shadowRoot', _shadowRoot);
  1689. }
  1690. // Partially based on https://greasyfork.org/en/scripts/22737-remove-yandex-redirect
  1691. let selectors = (
  1692. 'A[onmousedown*="/jsredir"],'+
  1693. 'A[data-vdir-href],'+
  1694. 'A[data-counter]'
  1695. );
  1696. let removeTrackingAttributes = function(link)
  1697. {
  1698. link.removeAttribute('onmousedown');
  1699. if (link.hasAttribute('data-vdir-href')) {
  1700. link.removeAttribute('data-vdir-href');
  1701. link.removeAttribute('data-orig-href');
  1702. }
  1703. if (link.hasAttribute('data-counter')) {
  1704. link.removeAttribute('data-counter');
  1705. link.removeAttribute('data-bem');
  1706. }
  1707. };
  1708. let removeTracking = function(scope)
  1709. {
  1710. for (let link of scope.querySelectorAll(selectors))
  1711. removeTrackingAttributes(link);
  1712. };
  1713. document.addEventListener('DOMContentLoaded', (e) => removeTracking(e.target));
  1714. (new MutationObserver(
  1715. function(ms)
  1716. {
  1717. let m, node;
  1718. for (m of ms) for (node of m.addedNodes) if (node.nodeType === Node.ELEMENT_NODE)
  1719. if (node.tagName === 'A' && node.matches(selectors)) {
  1720. removeTrackingAttributes(node);
  1721. } else {
  1722. removeTracking(node);
  1723. }
  1724. }
  1725. )).observe(_de, { childList: true, subtree: true });
  1726.  
  1727. //skip fixes for other sites
  1728. return;
  1729. }
  1730.  
  1731. // https://greasyfork.org/en/scripts/21937-moonwalk-hdgo-kodik-fix v0.8 (adapted)
  1732. document.addEventListener(
  1733. 'DOMContentLoaded', function()
  1734. {//createPlayer();
  1735. function log (name) {
  1736. console.log(`Player FIX: Detected ${name} player on ${location.href}`);
  1737. }
  1738. if (win.adv_enabled !== undefined && win.condition_detected !== undefined)
  1739. {
  1740. log('Moonwalk');
  1741. if (win.adv_enabled)
  1742. win.adv_enabled = false;
  1743. win.condition_detected = false;
  1744. if (win.MXoverrollCallback)
  1745. document.addEventListener(
  1746. 'click', function catcher(e)
  1747. {
  1748. e.stopPropagation();
  1749. win.MXoverrollCallback.call(window);
  1750. document.removeEventListener('click', catcher, true);
  1751. }, true
  1752. );
  1753. }
  1754. else if (win.stat_url !== undefined && win.is_html5 !== undefined && win.is_wp8 !== undefined)
  1755. {
  1756. log('HDGo');
  1757. document.body.onclick = null;
  1758. let tmp = document.querySelector('#swtf');
  1759. if (tmp)
  1760. tmp.style.display = 'none';
  1761. if (win.banner_second !== undefined)
  1762. win.banner_second = 0;
  1763. if (win.$banner_ads !== undefined)
  1764. win.$banner_ads = false;
  1765. if (win.$new_ads !== undefined)
  1766. win.$new_ads = false;
  1767. if (win.createCookie !== undefined)
  1768. win.createCookie('popup', 'true', '999');
  1769. if (win.canRunAds !== undefined && win.canRunAds !== true)
  1770. win.canRunAds = true;
  1771. }
  1772. else if (win.MXoverrollCallback && win.iframeSearch !== undefined)
  1773. {
  1774. log('Kodik');
  1775. let tmp = document.querySelector('.play_button');
  1776. if (tmp)
  1777. tmp.onclick = win.MXoverrollCallback.bind(window);
  1778. win.IsAdBlock = false;
  1779. }
  1780. else if (win.getnextepisode && win.uppodEvent)
  1781. {
  1782. log('Share-Serials.net');
  1783. scriptLander(
  1784. function()
  1785. {
  1786. let _setInterval = win.setInterval,
  1787. _setTimeout = win.setTimeout;
  1788. win.setInterval = function(func)
  1789. {
  1790. if (func instanceof Function && func.toString().indexOf('_delay') > -1)
  1791. {
  1792. let intv = _setInterval.call(
  1793. this, function()
  1794. {
  1795. _setTimeout.call(
  1796. this, function(intv)
  1797. {
  1798. clearInterval(intv);
  1799. let timer = document.querySelector('#timer');
  1800. if (timer)
  1801. timer.click();
  1802. }, 100, intv);
  1803. func.call(this);
  1804. }, 5
  1805. );
  1806.  
  1807. return intv;
  1808. }
  1809. return _setInterval.apply(this, arguments);
  1810. };
  1811. win.setTimeout = function(func) {
  1812. if (func instanceof Function && func.toString().indexOf('adv_showed') > -1)
  1813. {
  1814. return _setTimeout.call(this, func, 0);
  1815. }
  1816. return _setTimeout.apply(this, arguments);
  1817. };
  1818. }
  1819. );
  1820. } else if ('ADC' in win)
  1821. {
  1822. log('vjs-creatives plugin in');
  1823. let replacer = (obj) => {
  1824. for (let name in obj)
  1825. if (obj[name] instanceof Function)
  1826. obj[name] = () => null;
  1827. };
  1828. replacer(win.ADC);
  1829. replacer(win.currentAdSlot);
  1830. }
  1831. }, false
  1832. );
  1833.  
  1834. // piguiqproxy.com circumvention prevention
  1835. scriptLander(
  1836. () => {
  1837. let _open = XMLHttpRequest.prototype.open;
  1838. // blacklist of third-party domains requests to which are ignored
  1839. let blacklist = /[/.@](46p5gi\.ru|amgload\.net|k5evib\.ru|piguiqproxy\.com|rcdn\.pro)[:/]/i;
  1840. // blacklist of domains where all third-party requests are ignored
  1841. let ondomains = /(^|[/.@])oane\.ws($|[:/])/i;
  1842.  
  1843. XMLHttpRequest.prototype.open = function(method, url)
  1844. {
  1845. if (method === 'GET' && (blacklist.test(url) ||
  1846. ondomains.test(location.hostname) && !ondomains.test(url)))
  1847. {
  1848. this.send = () => null;
  1849. this.setRequestHeader = () => null;
  1850. console.log('Blocked request: ', url);
  1851. return;
  1852. }
  1853. return _open.apply(this, arguments);
  1854. };
  1855. }
  1856. );
  1857.  
  1858. // === Helper functions ===
  1859.  
  1860. // function to search and remove nodes by content
  1861. // selector - standard CSS selector to define set of nodes to check
  1862. // words - regular expression to check content of the suspicious nodes
  1863. // params - object with multiple extra parameters:
  1864. // .log - display log in the console
  1865. // .hide - set display to none instead of removing from the page
  1866. // .parent - parent node to remove if content is found in the child node
  1867. // .siblings - number of simling nodes to remove (excluding text nodes)
  1868. let scRemove = (node) => node.parentNode.removeChild(node);
  1869. let scHide = function(node)
  1870. {
  1871. let style = _getAttribute.call(node, 'style') || '',
  1872. hide = ';display:none!important;';
  1873. if (style.indexOf(hide) < 0)
  1874. _setAttribute.call(node, 'style', style + hide);
  1875. };
  1876.  
  1877. function scissors (selector, words, scope, params)
  1878. {
  1879. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1880. if (!scope.contains(document.body))
  1881. logger('[s] scope', scope);
  1882. let remFunc = (params.hide ? scHide : scRemove),
  1883. iterFunc = (params.siblings > 0 ? 'nextElementSibling' : 'previousElementSibling'),
  1884. toRemove = [],
  1885. siblings;
  1886. for (let node of scope.querySelectorAll(selector))
  1887. {
  1888. // drill up to a parent node if specified, break if not found
  1889. if (params.parent)
  1890. {
  1891. let old = node;
  1892. node = node.closest(params.parent);
  1893. if (node === null || node.contains(scope))
  1894. {
  1895. logger('[s] went out of scope with', old);
  1896. continue;
  1897. }
  1898. }
  1899. logger('[s] processing', node);
  1900. if (toRemove.includes(node))
  1901. continue;
  1902. if (words.test(node.innerHTML))
  1903. {
  1904. // skip node if already marked for removal
  1905. logger('[s] marked for removal');
  1906. toRemove.push(node);
  1907. // add multiple nodes if defined more than one sibling
  1908. siblings = Math.abs(params.siblings) || 0;
  1909. while (siblings)
  1910. {
  1911. node = node[iterFunc];
  1912. if (!node) break; // can't go any further - exit
  1913. logger('[s] adding sibling node', node);
  1914. toRemove.push(node);
  1915. siblings -= 1;
  1916. }
  1917. }
  1918. }
  1919. let toSkip = [];
  1920. for (let node of toRemove)
  1921. if (!toRemove.every(other => other === node || !node.contains(other)))
  1922. toSkip.push(node);
  1923. if (toRemove.length)
  1924. logger(`[s] proceeding with ${params.hide?'hide':'removal'} of`, toRemove, `skip`, toSkip);
  1925. for (let node of toRemove) if (!toSkip.includes(node))
  1926. remFunc(node);
  1927. }
  1928.  
  1929. // function to perform multiple checks if ads inserted with a delay
  1930. // by default does 30 checks withing a 3 seconds unless nonstop mode specified
  1931. // also does 1 extra check when a page completely loads
  1932. // selector and words - passed dow to scissors
  1933. // params - object with multiple extra parameters:
  1934. // .log - display log in the console
  1935. // .root - selector to narrow down scope to scan;
  1936. // .observe - if true then check will be performed continuously;
  1937. // Other parameters passed down to scissors.
  1938. function gardener(selector, words, params)
  1939. {
  1940. let logger = function() { return params.log ? console.log(...arguments) : null; };
  1941. params = params || {};
  1942. logger(`[gardener] selector: '${selector}' detector: ${words} options: ${JSON.stringify(params)}`);
  1943. let scope;
  1944. let globalScope = [_de];
  1945. let domLoaded = false;
  1946. let getScope = root => root ? _de.querySelectorAll(root) : globalScope;
  1947. let onevent = e => {
  1948. logger(`[gardener] cleanup on ${Object.getPrototypeOf(e)} "${e.type}"`);
  1949. for (let node of scope)
  1950. scissors(selector, words, node, params);
  1951. };
  1952. let repeater = n => {
  1953. if (!domLoaded && n) {
  1954. setTimeout(repeater, 500, n - 1);
  1955. scope = getScope(params.root);
  1956. if (!scope) // exit if the root element is not present on the page
  1957. return 0;
  1958. onevent({type: 'Repeater'});
  1959. }
  1960. };
  1961. repeater(20);
  1962. document.addEventListener(
  1963. 'DOMContentLoaded', (e) => {
  1964. domLoaded = true;
  1965. // narrow down scope to a specific element
  1966. scope = getScope(params.root);
  1967. if (!scope) // exit if the root element is not present on the page
  1968. return 0;
  1969. logger('[g] scope', scope);
  1970. // add observe mode if required
  1971. if (params.observe)
  1972. {
  1973. let params = { childList:true, subtree: true };
  1974. let observer = new MutationObserver(
  1975. function(ms)
  1976. {
  1977. for (let m of ms)
  1978. if (m.addedNodes.length)
  1979. onevent(m);
  1980. }
  1981. );
  1982. for (let node of scope)
  1983. observer.observe(node, params);
  1984. logger('[g] observer enabled');
  1985. }
  1986. onevent(e);
  1987. }, false);
  1988. // wait for a full page load to do one extra cut
  1989. win.addEventListener('load', onevent, false);
  1990. }
  1991.  
  1992. // wrap popular methods to open a new tab to catch specific behaviours
  1993. function createWindowOpenWrapper(openFunc, onClickFunc)
  1994. {
  1995. let _createElement = Document.prototype.createElement,
  1996. _appendChild = Element.prototype.appendChild,
  1997. fakeNative = (f) => (f.toString = () => `function ${f.name}() { [native code] }`);
  1998.  
  1999. let nt = new nullTools();
  2000. fakeNative(openFunc);
  2001.  
  2002. let parser = _createElement.call(document, 'a');
  2003. let openWhitelist = (url) => {
  2004. parser.href = url;
  2005. return parser.hostname === 'www.imdb.com' || parser.hostname === 'www.kinopoisk.ru';
  2006. };
  2007.  
  2008. let redefineOpen = (obj) => {
  2009. for (let root of [obj, obj.document, obj.Document.prototype]) if ('open' in root) {
  2010. let _open = root.open.bind(root);
  2011. nt.define(root, 'open', (...args) => {
  2012. if (openWhitelist(args[0])) {
  2013. console.log('Whitelisted popup:', ...args);
  2014. return _open(...args);
  2015. }
  2016. return openFunc(...args);
  2017. });
  2018. }
  2019. };
  2020. redefineOpen(win);
  2021.  
  2022. function createElement(name) {
  2023. '[native code]';
  2024. // jshint validthis:true
  2025. let el = _createElement.apply(this, arguments);
  2026. // click-dispatch check for Google Chrome and similar browsers
  2027. if (el instanceof HTMLAnchorElement)
  2028. el.addEventListener('click', onClickFunc, false);
  2029. // redefine window.open in first-party frames
  2030. if (el instanceof HTMLIFrameElement || el instanceof HTMLObjectElement)
  2031. el.addEventListener('load', (e) => {
  2032. try {
  2033. redefineOpen(e.target.contentWindow);
  2034. } catch(ignore) {}
  2035. }, false);
  2036. return el;
  2037. }
  2038. fakeNative(createElement);
  2039.  
  2040. let redefineCreateElement = (obj) => {
  2041. for (let root of [obj.document, obj.Document.prototype]) if ('createElement' in root)
  2042. nt.define(root, 'createElement', createElement);
  2043. };
  2044. redefineCreateElement(win);
  2045.  
  2046. // wrap window.open in newly added first-party frames
  2047. Element.prototype.appendChild = function appendChild()
  2048. {
  2049. '[native code]';
  2050. let el = _appendChild.apply(this, arguments);
  2051. if (el instanceof HTMLIFrameElement) {
  2052. try {
  2053. redefineOpen(el.contentWindow);
  2054. redefineCreateElement(el.contentWindow);
  2055. } catch(ignore) {}
  2056. }
  2057. return el;
  2058. };
  2059. fakeNative(Element.prototype.appendChild);
  2060. }
  2061.  
  2062. // Function to catch and block various methods to open a new window with 3rd-party content.
  2063. // Some advertisement networks went way past simple window.open call to circumvent default popup protection.
  2064. // This funciton blocks window.open, ability to restore original window.open from an IFRAME object,
  2065. // ability to perform an untrusted (not initiated by user) click on a link, click on a link without a parent
  2066. // node or simply a link with piece of javascript code in the HREF attribute.
  2067. function preventPopups()
  2068. {
  2069. // call sandbox-me if in iframe and not whitelisted
  2070. if (inIFrame) {
  2071. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2072. return;
  2073. }
  2074.  
  2075. scriptLander(() => {
  2076. let open = (...args) => {
  2077. '[native code]';
  2078. console.warn('Site attempted to open a new window', args);
  2079. if (new RegExp(`^https?://${location.hostname}/`).test(args[0])) // skip extra click in case of blocked popunder
  2080. location.assign(args[0]);
  2081. return {
  2082. document: {
  2083. write: () => {},
  2084. writeln: () => {}
  2085. }
  2086. };
  2087. };
  2088.  
  2089. let clickHandler = (e) => {
  2090. let link = e.target;
  2091. if (!link.parentNode || !e.isTrusted ||
  2092. (link.href && link.href.trim().toLowerCase().indexOf('javascript') === 0))
  2093. {
  2094. e.preventDefault();
  2095. console.warn('Blocked suspicious click event', e, 'on', e.target);
  2096. }
  2097. };
  2098.  
  2099. createWindowOpenWrapper(open, clickHandler);
  2100.  
  2101. console.log('Popup prevention enabled.');
  2102. }, nullTools, createWindowOpenWrapper);
  2103. }
  2104.  
  2105. // Helper function to close background tab if site opens itself in a new tab and then
  2106. // loads a 3rd-party page in the background one (thus performing background redirect).
  2107. function preventPopunders()
  2108. {
  2109. // create "close_me" event to call high-level window.close()
  2110. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2111. let callClose = () => (console.log('close call'), window.close());
  2112. window.addEventListener(eventName, callClose, true);
  2113.  
  2114. scriptLander(() => {
  2115. // get host of a provided URL with help of an anchor object
  2116. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2117. let parseURL = document.createElement('A');
  2118. let getHost = (url) => (parseURL.href = url, parseURL.hostname);
  2119. // site went to a new tab and attempts to unload
  2120. // call for high-level close through event
  2121. let closeWindow = () => window.dispatchEvent(new CustomEvent(eventName, {}));
  2122. // check is URL local or goes to different site
  2123. let isLocal = (url) => {
  2124. if (url === location.pathname || url === location.href)
  2125. return true; // URL points to current pathname or full address
  2126. let host = getHost(url);
  2127. let site = location.hostname;
  2128. return host !== '' && // URLs with unusual protocol may have empty 'host'
  2129. (site === host || site.endsWith(`.${host}`) || host.endsWith(`.${site}`));
  2130. };
  2131.  
  2132. let _open = window.open.bind(window);
  2133. let open = (...args) => {
  2134. '[native code]';
  2135. let url = args[0];
  2136. if (url && isLocal(url))
  2137. window.addEventListener('beforeunload', closeWindow, true);
  2138. // jshint validthis:true
  2139. return _open(...args);
  2140. };
  2141.  
  2142. let clickHandler = (e) => {
  2143. if (!e.target.parentNode || !e.isTrusted)
  2144. window.addEventListener('beforeunload', closeWindow, true);
  2145. };
  2146.  
  2147. createWindowOpenWrapper(open, clickHandler);
  2148.  
  2149. console.log("Background redirect prevention enabled.");
  2150. }, `let eventName="${eventName}"`, nullTools, createWindowOpenWrapper);
  2151. }
  2152.  
  2153. // Mix between check for popups and popunders
  2154. // Significantly more agressive than both and can't be used as universal solution
  2155. function preventPopMix()
  2156. {
  2157. if (inIFrame)
  2158. {
  2159. win.top.postMessage({ name: 'sandbox-me', href: win.location.href }, '*');
  2160. return;
  2161. }
  2162.  
  2163. // create "close_me" event to call high-level window.close()
  2164. let eventName = `close_me_${Math.random().toString(36).substr(2)}`;
  2165. let callClose = () => (console.log('close call'), window.close());
  2166. window.addEventListener(eventName, callClose, true);
  2167.  
  2168. scriptLander(() => {
  2169. let _open = window.open,
  2170. parseURL = document.createElement('A');
  2171. // get host of a provided URL with help of an anchor object
  2172. // unfortunately new URL(url, window.location) generates wrong URL in some cases
  2173. let getHost = (url) => (parseURL.href = url, parseURL.host);
  2174. // site went to a new tab and attempts to unload
  2175. // call for high-level close through event
  2176. let closeWindow = () => (_open(window.location,'_self'), window.dispatchEvent(new CustomEvent(eventName, {})));
  2177. // check is URL local or goes to different site
  2178. function isLocal(url)
  2179. {
  2180. let loc = window.location;
  2181. if (url === loc.pathname || url === loc.href)
  2182. return true; // URL points to current pathname or full address
  2183. let host = getHost(url),
  2184. site = loc.host;
  2185. if (host === '')
  2186. return false; // URLs with unusual protocol may have empty 'host'
  2187. if (host.length > site.length)
  2188. [site, host] = [host, site];
  2189. return site.includes(host, site.length - host.length);
  2190. }
  2191.  
  2192. // add check for redirect for 5 seconds, then disable it
  2193. function checkRedirect()
  2194. {
  2195. window.addEventListener('beforeunload', closeWindow, true);
  2196. setTimeout(closeWindow=>window.removeEventListener('beforeunload', closeWindow, true), 5000, closeWindow);
  2197. }
  2198.  
  2199. function open(url, name)
  2200. {
  2201. '[native code]';
  2202. if (url && isLocal(url) && (!name || name === '_blank'))
  2203. {
  2204. console.warn('Suspicious local new window', arguments);
  2205. checkRedirect();
  2206. // jshint validthis:true
  2207. return _open.apply(this, arguments);
  2208. }
  2209. console.warn('Blocked attempt to open a new window', arguments);
  2210. return {
  2211. document: {
  2212. write: () => {},
  2213. writeln: () => {}
  2214. }
  2215. };
  2216. }
  2217.  
  2218. function clickHandler(e)
  2219. {
  2220. let link = e.target,
  2221. url = link.href||'';
  2222. if (e.targetParentNode && e.isTrusted || link.target !== '_blank')
  2223. {
  2224. console.log('Link', link, 'were created dinamically, but looks fine.');
  2225. return true;
  2226. }
  2227. if (isLocal(url) && link.target === '_blank')
  2228. {
  2229. console.log('Suspicious local link', link);
  2230. checkRedirect();
  2231. return;
  2232. }
  2233. console.log('Blocked suspicious click on a link', link);
  2234. e.stopPropagation();
  2235. e.preventDefault();
  2236. }
  2237.  
  2238. createWindowOpenWrapper(open, clickHandler);
  2239.  
  2240. console.log("Mixed popups prevention enabled.");
  2241. }, `let eventName="${eventName}"`, createWindowOpenWrapper);
  2242. }
  2243. // External listener for case when site known to open popups were loaded in iframe
  2244. // It will sandbox any iframe which will send message 'forbid.popups' (preventPopups sends it)
  2245. // Some sites replace frame's window.location with data-url to run in clean context
  2246. if (!inIFrame)
  2247. {
  2248. window.addEventListener(
  2249. 'message', function(e)
  2250. {
  2251. if (!e.data || e.data.name !== 'sandbox-me' || !e.data.href)
  2252. return;
  2253. let src = e.data.href;
  2254. for (let frame of document.querySelectorAll('iframe'))
  2255. if (frame.contentWindow === e.source)
  2256. {
  2257. if (frame.hasAttribute('sandbox'))
  2258. {
  2259. if (!frame.sandbox.contains('allow-popups'))
  2260. return; // exit frame since it's already sandboxed and popups are blocked
  2261. // remove allow-popups if frame already sandboxed
  2262. frame.sandbox.remove('allow-popups');
  2263. } else {
  2264. // set sandbox mode for troublesome frame and allow scripts, forms and a few other actions
  2265. // technically allowing both scripts and same-origin allows removal of the sandbox attribute,
  2266. // but to apply content must be reloaded and this script will re-apply it in the result
  2267. frame.setAttribute('sandbox','allow-forms allow-scripts allow-presentation allow-top-navigation allow-same-origin');
  2268. }
  2269. console.log('Disallowed popups from iframe', frame);
  2270.  
  2271. // reload frame content to apply restrictions
  2272. if (!src) {
  2273. src = frame.src;
  2274. console.log('Unable to get current iframe location, reloading from src', src);
  2275. } else
  2276. console.log('Reloading iframe with URL', src);
  2277. frame.src = 'about:blank';
  2278. frame.src = src;
  2279. }
  2280. }, false
  2281. );
  2282. }
  2283.  
  2284. function selectiveEval() {
  2285. scriptLander(() => {
  2286. let nt = new nullTools();
  2287. let _eval = win.eval.bind(window);
  2288. nt.define(win, 'eval', function(...args) {
  2289. if (/_0x|location\s*?=|location.href\s*?=|location.assign\(|open\(/i.test(args[0])) {
  2290. console.log(`Skipped eval of ${args[0].slice(0, 512)}\u2026`);
  2291. return null;
  2292. }
  2293. return _eval(...args);
  2294. });
  2295. }, nullTools);
  2296. }
  2297.  
  2298. // === Scripts for specific domains ===
  2299.  
  2300. let scripts = {};
  2301. // prevent popups and redirects block
  2302. // Popups
  2303. scripts.preventPopups = {
  2304. other: [
  2305. 'biqle.ru',
  2306. 'chaturbate.com',
  2307. 'dfiles.ru',
  2308. 'hentaiz.org',
  2309. 'mirrorcreator.com',
  2310. 'online-multy.ru',
  2311. 'radikal.ru', 'rumedia.ws',
  2312. 'seedoff.cc', 'seedoff.tv',
  2313. 'thepiratebay.org', 'torseed.net',
  2314. 'unionpeer.com',
  2315. 'zippyshare.com'
  2316. ],
  2317. now: preventPopups
  2318. };
  2319. // Popunders (background redirect)
  2320. scripts.preventPopunders = {
  2321. other: [
  2322. 'lostfilm-online.ru',
  2323. 'mediafire.com', 'megapeer.org', 'megapeer.ru',
  2324. 'perfectgirls.net'
  2325. ],
  2326. now: preventPopunders
  2327. };
  2328. // PopMix (both types of popups encountered on site)
  2329. scripts['openload.co'] = {
  2330. other: ['oload.tv', 'oload.info'],
  2331. now: () => {
  2332. let nt = new nullTools();
  2333. nt.define(win, 'CNight', win.CoinHive);
  2334. if (location.pathname.startsWith('/embed/'))
  2335. {
  2336. nt.define(win, 'BetterJsPop', {
  2337. add: ((a, b) => console.warn('BetterJsPop.add', a, b)),
  2338. config: ((o) => console.warn('BetterJsPop.config', o)),
  2339. Browser: { isChrome: true }
  2340. });
  2341. nt.define(win, 'isSandboxed', nt.func(null));
  2342. nt.define(win, 'adblock', false);
  2343. nt.define(win, 'adblock2', false);
  2344. } else
  2345. preventPopMix();
  2346. }
  2347. };
  2348. scripts['turbobit.net'] = preventPopMix;
  2349.  
  2350. // workaround for moradu.com/apu.php load error handler script, not sure which ad network is this
  2351. scripts['tapochek.net'] = () => {
  2352. let _appendChild = Object.getOwnPropertyDescriptor(Node.prototype, 'appendChild');
  2353. let _appendChild_value = _appendChild.value;
  2354. _appendChild.value = function appendChild(node) {
  2355. if (this === win.document.body)
  2356. if ((node instanceof HTMLScriptElement || node instanceof HTMLStyleElement) &&
  2357. /^https?:\/\/[0-9a-f]{15}\.com\/\d+(\/|\.css)$/.test(node.src) ||
  2358. node instanceof HTMLDivElement && node.style.zIndex > 900000 &&
  2359. node.style.backgroundImage.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'))
  2360. throw '...eenope!';
  2361. return _appendChild_value.apply(this, arguments);
  2362. };
  2363. Object.defineProperty(Node.prototype, 'appendChild', _appendChild);
  2364.  
  2365. preventPopups();
  2366. };
  2367.  
  2368. // scripts['lostfilm-online.ru'] = () => scriptLander(() => {
  2369. //
  2370. // });
  2371.  
  2372. scripts['rustorka.com'] = {
  2373. other: ['rustorka.lib'],
  2374. dom: () => scriptLander(() => {
  2375. let link = void 0;
  2376. document.body.addEventListener('mousedown', e => {
  2377. link = e.target.closest('a, select');
  2378. }, false);
  2379. let _open = window.open.bind(window);
  2380. let _getAttribute = Element.prototype.getAttribute;
  2381. win.open = (...args) => {
  2382. let url = args[0];
  2383. let allow = false;
  2384. if (link instanceof HTMLAnchorElement) {
  2385. // third-party post links
  2386. let href = _getAttribute.call(link, 'href');
  2387. if (link.classList.contains('postLink') &&
  2388. !link.matches(`a[href*="${location.hostname}"]`) &&
  2389. (href === url || link.href === url)) {
  2390. return _open(...args);
  2391. }
  2392. // onclick # links
  2393. if (href === '#' && /window\.open/.test(_getAttribute.call(link, 'onclick'))) {
  2394. return _open(...args);
  2395. }
  2396. // force local links to load in the current window
  2397. if (href.includes(`//${location.hostname}/`))
  2398. location.assign(href);
  2399. }
  2400. // list of image hostings under upload picture button (new comment)
  2401. if (link instanceof HTMLSelectElement &&
  2402. !url.includes(location.hostname) &&
  2403. link.value === url) {
  2404. return _open(...args);
  2405. }
  2406. // looks like tabunder
  2407. if (link === null && url === location.href)
  2408. location.replace(url); // reload current page
  2409. // other cases
  2410. console.warn(`Site attempted to open "${url}" in a new window. Source: `, link);
  2411. return {};
  2412. };
  2413. })
  2414. };
  2415.  
  2416. // other
  2417. scripts['1tv.ru'] = () => scriptLander(() => {
  2418. let nt = new nullTools();
  2419. nt.define(win, 'EUMPAntiblockConfig', nt.proxy({url: '//www.1tv.ru/favicon.ico'}));
  2420. let _EUMPConfig = void 0;
  2421. let disablePlugins = {
  2422. 'antiblock': false,
  2423. 'stat1tv': false
  2424. };
  2425. Object.defineProperty(win, 'EUMPConfig', {
  2426. enumerable: true,
  2427. get: x => _EUMPConfig,
  2428. set: x => {
  2429. let plugins = x.plugins;
  2430. if (plugins) {
  2431. let id;
  2432. for (let plugin in disablePlugins) {
  2433. id = plugins.indexOf(plugin);
  2434. if (id > -1) {
  2435. plugins.splice(id, 1);
  2436. disablePlugins[plugin] = true;
  2437. }
  2438. }
  2439. console.warn(`Player plugins: active [${plugins}], disabled [${Object.keys(disablePlugins).filter(x => disablePlugins[x])}]`);
  2440. }
  2441. _EUMPConfig = x;
  2442. }
  2443. });
  2444. }, nullTools);
  2445.  
  2446. scripts['2picsun.ru'] = {
  2447. other: [
  2448. 'pics2sun.ru', '3pics-img.ru'
  2449. ],
  2450. now: () => {
  2451. Object.defineProperty(navigator, 'userAgent', {value: 'googlebot'});
  2452. }
  2453. };
  2454.  
  2455. scripts['4pda.ru'] = {
  2456. now: () => {
  2457. // https://greasyfork.org/en/scripts/14470-4pda-unbrender
  2458. let hStyle,
  2459. isForum = document.location.href.search('/forum/') !== -1,
  2460. remove = (node) => (node ? node.parentNode.removeChild(node) : null),
  2461. afterClean = () => remove(hStyle);
  2462.  
  2463. function beforeClean()
  2464. {
  2465. // attach styles before document displayed
  2466. hStyle = createStyle([
  2467. 'html { overflow-y: scroll }',
  2468. 'article + aside * { display: none !important }',
  2469. `section[id] {${(
  2470. 'position: absolute;'+
  2471. 'width: 100%'
  2472. )}}`,
  2473. `#header + div:after {${(
  2474. 'content: "";'+
  2475. 'position: fixed;'+
  2476. 'top: 0;'+
  2477. 'left: 0;'+
  2478. 'width: 100%;'+
  2479. 'height: 100%;'+
  2480. 'background-color: #E6E7E9'
  2481. )}}`,
  2482. // http://codepen.io/Beaugust/pen/DByiE
  2483. '@keyframes spin { 100% { transform: rotate(360deg) } }',
  2484. `article + aside:after {${(
  2485. 'content: "";'+
  2486. 'position: absolute;'+
  2487. 'width: 150px;'+
  2488. 'height: 150px;'+
  2489. 'top: 150px;'+
  2490. 'left: 50%;'+
  2491. 'margin-top: -75px;'+
  2492. 'margin-left: -75px;'+
  2493. 'box-sizing: border-box;'+
  2494. 'border-radius: 100%;'+
  2495. 'border: 10px solid rgba(0, 0, 0, 0.2);'+
  2496. 'border-top-color: rgba(0, 0, 0, 0.6);'+
  2497. 'animation: spin 2s infinite linear'
  2498. )}}`
  2499. ], {id:'ubrHider'}, true);
  2500.  
  2501. // display content of a page if time to load a page is more than 2 seconds to avoid
  2502. // blocking access to a page if it is loading for too long or stuck in a loading state
  2503. setTimeout(2000, afterClean);
  2504. }
  2505.  
  2506. createStyle([
  2507. '#nav .use-ad { display: block !important }',
  2508. 'article:not(.post) + article:not(#id),'+
  2509. 'html:not(#id)>body:not(#id) a[target="_blank"] img[height="90"] { display: none !important }'
  2510. ]);
  2511.  
  2512. if (!isForum)
  2513. beforeClean();
  2514.  
  2515. // save links to non-overridden functions to use later
  2516. let protectedElems;
  2517. // protect/hide changed attributes in case site attempt to restore them
  2518. function styleProtector(eventMode)
  2519. {
  2520. let _toLowerCase = String.prototype.toLowerCase,
  2521. isStyleText = (t) => (_toLowerCase.call(t) === 'style'),
  2522. protectedElems = new WeakMap();
  2523. function protoOverride(element, functionName, isStyleCheck, returnIfProtected)
  2524. {
  2525. let originalFunction = element.prototype[functionName];
  2526. element.prototype[functionName] = function wrapper()
  2527. {
  2528. if (protectedElems.has(this) && isStyleCheck(arguments[0]))
  2529. return returnIfProtected(this, arguments);
  2530. return originalFunction.apply(this, arguments);
  2531. };
  2532. }
  2533. protoOverride(Element, 'removeAttribute', isStyleText, () => undefined);
  2534. protoOverride(Element, 'hasAttribute', isStyleText, (_this) => protectedElems.get(_this) !== null);
  2535. protoOverride(Element, 'setAttribute', isStyleText, (_this, args) => protectedElems.set(_this, args[1]));
  2536. protoOverride(Element, 'getAttribute', isStyleText, (_this) => protectedElems.get(_this));
  2537. if (!eventMode)
  2538. return protectedElems;
  2539. else
  2540. {
  2541. let e = document.createEvent('Event');
  2542. e.initEvent('protoOverride', false, false);
  2543. window.protectedElems = protectedElems;
  2544. window.dispatchEvent(e);
  2545. }
  2546. }
  2547. if (!isFirefox)
  2548. protectedElems = styleProtector(false);
  2549. else
  2550. {
  2551. let script = document.createElement('script');
  2552. script.textContent = `(${styleProtector.toString()})(true);`;
  2553. window.addEventListener(
  2554. 'protoOverride', function protoOverrideCallback(e)
  2555. {
  2556. if (win.protectedElems) {
  2557. protectedElems = win.protectedElems;
  2558. delete win.protectedElems;
  2559. }
  2560. document.removeEventListener('protoOverride', protoOverrideCallback, true);
  2561. }, true
  2562. );
  2563. _appendChild(script);
  2564. _removeChild(script);
  2565. }
  2566.  
  2567. // clean a page
  2568. window.addEventListener(
  2569. 'DOMContentLoaded', function()
  2570. {
  2571. let width = () => window.innerWidth || _de.clientWidth || document.body.clientWidth || 0;
  2572. let height = () => window.innerHeight || _de.clientHeight || document.body.clientHeight || 0;
  2573.  
  2574. if (isForum)
  2575. {
  2576. let si = document.querySelector('#logostrip');
  2577. if (si)
  2578. remove(si.parentNode.nextSibling);
  2579. }
  2580.  
  2581. // clear background in the download frame
  2582. if (location.pathname.startsWith('/forum/dl/')) {
  2583. let setBackground = node => _setAttribute.call(
  2584. node,
  2585. 'style', (_getAttribute.call(node, 'style') || '') +
  2586. ';background-color:#4ebaf6!important'
  2587. );
  2588. setBackground(document.body);
  2589. for (let itm of document.querySelectorAll('body > div'))
  2590. if (!itm.querySelector('.dw-fdwlink, .content') && !itm.classList.contains('footer')) {
  2591. remove(itm);
  2592. } else {
  2593. setBackground(itm);
  2594. }
  2595. }
  2596.  
  2597. if (isForum) // Do not continue if it's a forum
  2598. return;
  2599.  
  2600. {
  2601. let si = document.querySelector('#header');
  2602. if (si)
  2603. {
  2604. let rem = si.previousSibling;
  2605. while (rem)
  2606. {
  2607. si = rem.previousSibling;
  2608. remove(rem);
  2609. rem = si;
  2610. }
  2611. }
  2612. }
  2613.  
  2614. for (let itm of document.querySelectorAll('#nav li[class]'))
  2615. if (itm && itm.querySelector('a[href^="/tag/"]'))
  2616. remove(itm);
  2617.  
  2618. let style, result,
  2619. fakeStyles = new WeakMap(),
  2620. styleProxy = {
  2621. get: function(target, prop)
  2622. {
  2623. let fakeStyle = fakeStyles.get(target);
  2624. return ((prop in fakeStyle) ? fakeStyle : target)[prop];
  2625. },
  2626. set: function(target, prop, value)
  2627. {
  2628. let fakeStyle = fakeStyles.get(target);
  2629. ((prop in fakeStyle) ? fakeStyle : target)[prop] = value;
  2630. return true;
  2631. }
  2632. };
  2633. for (let itm of document.querySelectorAll('DIV, A'))
  2634. {
  2635. if (itm.tagName ==='DIV' &&
  2636. itm.offsetWidth > 0.95 * width() &&
  2637. itm.offsetHeight > 0.85 * height())
  2638. {
  2639. style = window.getComputedStyle(itm, null);
  2640. result = [];
  2641.  
  2642. if (style.backgroundImage !== 'none')
  2643. result.push('background-image:none!important');
  2644.  
  2645. if (style.backgroundColor !== 'transparent' &&
  2646. style.backgroundColor !== 'rgba(0, 0, 0, 0)')
  2647. result.push('background-color:transparent!important');
  2648.  
  2649. if (result.length)
  2650. {
  2651. if (itm.getAttribute('style'))
  2652. result.unshift(itm.getAttribute('style'));
  2653.  
  2654. fakeStyles.set(itm.style, {
  2655. 'backgroundImage': itm.style.backgroundImage,
  2656. 'backgroundColor': itm.style.backgroundColor
  2657. });
  2658.  
  2659. try {
  2660. Object.defineProperty(itm, 'style', {
  2661. value: new Proxy(itm.style, styleProxy),
  2662. enumerable: true
  2663. });
  2664. } catch (e) {
  2665. console.log('Unable to protect style property.', e);
  2666. }
  2667.  
  2668. if (protectedElems)
  2669. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2670.  
  2671. _setAttribute.call(itm, 'style', result.join(';'));
  2672. }
  2673. }
  2674. if (itm.tagName ==='A' &&
  2675. (itm.offsetWidth > 0.95 * width() ||
  2676. itm.offsetHeight > 0.85 * height()))
  2677. {
  2678. if (protectedElems)
  2679. protectedElems.set(itm, _getAttribute.call(itm, 'style'));
  2680.  
  2681. _setAttribute.call(itm, 'style', 'display:none!important');
  2682. }
  2683. }
  2684.  
  2685. for (let itm of document.querySelectorAll('ASIDE>DIV'))
  2686. if ( ((itm.querySelector('script, iframe, a[href*="/ad/www/"]') ||
  2687. itm.querySelector('img[src$=".gif"]:not([height="0"]), img[height="400"]')) &&
  2688. !itm.classList.contains('post') ) || !itm.childNodes.length )
  2689. remove(itm);
  2690.  
  2691. document.body.setAttribute('style', (document.body.getAttribute('style')||'')+';background-color:#E6E7E9!important');
  2692.  
  2693. // display content of the page
  2694. afterClean();
  2695. }
  2696. );
  2697. }
  2698. };
  2699.  
  2700. scripts['adhands.ru'] = () => scriptLander(() => {
  2701. let nt = new nullTools();
  2702. try {
  2703. let _adv;
  2704. Object.defineProperty(win, 'adv', {
  2705. get: () => _adv,
  2706. set: (v) => {
  2707. console.log('Blocked advert on adhands.ru.');
  2708. nt.define(v, 'advert', '');
  2709. _adv = v;
  2710. }
  2711. });
  2712. } catch (ignore) {
  2713. if (!win.adv)
  2714. console.log('Unable to locate advert on adhands.ru.');
  2715. else {
  2716. console.log('Blocked advert on adhands.ru.');
  2717. nt.define(win.adv, 'advert', '');
  2718. }
  2719. }
  2720. }, nullTools);
  2721.  
  2722. scripts['allhentai.ru'] = () => {
  2723. selectiveEval();
  2724. preventPopups();
  2725. scriptLander(() => {
  2726. let _onerror = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onerror');
  2727. if (!_onerror)
  2728. return;
  2729. _onerror.set = (...args) => console.log(args[0].toString());
  2730. Object.defineProperty(HTMLElement.prototype, 'onerror', _onerror);
  2731. });
  2732. };
  2733.  
  2734. scripts['allmovie.pro'] = {
  2735. other: ['rufilmtv.org'],
  2736. dom: function()
  2737. {
  2738. // pretend to be Android to make site use different played for ads
  2739. if (isSafari)
  2740. return;
  2741. Object.defineProperty(navigator, 'userAgent', {
  2742. get: function(){ 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'; },
  2743. enumerable: true
  2744. });
  2745. }
  2746. };
  2747.  
  2748. scripts['anidub-online.ru'] = {
  2749. other: ['online.anidub.com'],
  2750. dom: function()
  2751. {
  2752. if (win.ogonekstart1)
  2753. win.ogonekstart1 = () => console.log("Fire in the hole!");
  2754. },
  2755. now: () => createStyle([
  2756. '.background {background: none!important;}',
  2757. '.background > script + div,'+
  2758. '.background > script ~ div:not([id]):not([class]) + div[id][class]'+
  2759. '{display:none!important}'
  2760. ])
  2761. };
  2762.  
  2763. scripts['drive2.ru'] = () => gardener('.c-block:not([data-metrika="recomm"]),.o-grid__item', />Реклама<\//i);
  2764.  
  2765. scripts['fishki.net'] = () => {
  2766. scriptLander(() => {
  2767. let nt = new nullTools();
  2768. let fishki = {};
  2769. nt.define(fishki, 'adv', nt.proxy({
  2770. afterAdblockCheck: nt.func(null),
  2771. refreshFloat: nt.func(null)
  2772. }));
  2773. nt.define(fishki, 'is_adblock', false);
  2774. nt.define(win, 'fishki', fishki);
  2775. }, nullTools);
  2776. gardener('.drag_list > .drag_element, .list-view > .paddingtop15, .post-wrap', /543769|Новости\sпартнеров|Полезная\sреклама/);
  2777. };
  2778.  
  2779. scripts['gidonline.club'] = () => createStyle('.tray > div[style] {display: none!important}');
  2780.  
  2781. scripts['hdgo.cc'] = {
  2782. other: ['46.30.43.38', 'couber.be'],
  2783. now: () => (new MutationObserver(
  2784. (ms) => {
  2785. let m, node;
  2786. for (m of ms) for (node of m.addedNodes)
  2787. if (node.tagName instanceof HTMLScriptElement && _getAttribute.call(node, 'onerror') !== null)
  2788. node.removeAttribute('onerror');
  2789. }
  2790. )).observe(document.documentElement, { childList:true, subtree: true })
  2791. };
  2792.  
  2793. scripts['gismeteo.ru'] = {
  2794. other: ['gismeteo.ua'],
  2795. now: () => gardener('div > script', /AdvManager/i, { observe: true, parent: 'div' })
  2796. };
  2797.  
  2798. scripts['hdrezka.ag'] = () => {
  2799. Object.defineProperty(win, 'ab', { value: false, enumerable: true });
  2800. gardener('div[id][onclick][onmouseup][onmousedown]', /onmouseout/i);
  2801. };
  2802.  
  2803. scripts['hideip.me'] = {
  2804. now: () => scriptLander(() => {
  2805. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  2806. let _set_innerHTML = _innerHTML.set;
  2807. let _innerText = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'innerText');
  2808. let _get_innerText = _innerText.get;
  2809. let div = document.createElement('div');
  2810. _innerHTML.set = function(...args) {
  2811. _set_innerHTML.call(div, args[0].replace('i','a'));
  2812. if (args[0] && /[рp][еe]кл/.test(_get_innerText.call(div))||
  2813. /(\d\d\d?\.){3}\d\d\d?\:\d/.test(_get_innerText.call(this)) ) {
  2814. console.log('Anti-Adblock killed.');
  2815. return true;
  2816. }
  2817. _set_innerHTML.apply(this, args);
  2818. };
  2819. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  2820. Object.defineProperty(win, 'adblock', {
  2821. get: x => false,
  2822. set: x => null,
  2823. enumerable: true
  2824. });
  2825. let _$ = {};
  2826. let _$_map = new WeakMap();
  2827. let _gOPD = Object.getOwnPropertyDescriptor(Object, 'getOwnPropertyDescriptor');
  2828. let _val_gOPD = _gOPD.value;
  2829. _gOPD.value = function(...args) {
  2830. let _res = _val_gOPD.apply(this, args);
  2831. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery')) {
  2832. delete _res.get;
  2833. delete _res.set;
  2834. _res.value = win[args[1]];
  2835. }
  2836. return _res;
  2837. };
  2838. Object.defineProperty(Object, 'getOwnPropertyDescriptor', _gOPD);
  2839. let getJQWrap = (n) => {
  2840. let name = n;
  2841. return {
  2842. enumerable: true,
  2843. get: x => _$[name],
  2844. set: x => {
  2845. if (_$_map.has(x)) {
  2846. _$[name] = _$_map.get(x);
  2847. return true;
  2848. }
  2849. if (x === _$.$ || x === _$.jQuery) {
  2850. _$[name] = x;
  2851. return true;
  2852. }
  2853. _$[name] = new Proxy(x, {
  2854. apply: (t, o, args) => {
  2855. let _res = t.apply(o, args);
  2856. if (_$_map.has(_res.is)) {
  2857. _res.is = _$_map.get(_res.is);
  2858. } else {
  2859. let _is = _res.is;
  2860. _res.is = function(...args) {
  2861. if (args[0] === ':hidden')
  2862. return false;
  2863. return _is.apply(this, args);
  2864. };
  2865. _$_map.set(_is, _res.is);
  2866. }
  2867. return _res;
  2868. }
  2869. });
  2870. _$_map.set(x, _$[name]);
  2871. return true;
  2872. }
  2873. };
  2874. };
  2875. Object.defineProperty(win, '$', getJQWrap('$'));
  2876. Object.defineProperty(win, 'jQuery', getJQWrap('jQuery'));
  2877. let _dP = Object.defineProperty;
  2878. Object.defineProperty = function(...args) {
  2879. if (args[0] instanceof Window && (args[1] === '$' || args[1] === 'jQuery'))
  2880. return void 0;
  2881. return _dP.apply(this, args);
  2882. };
  2883. })
  2884. };
  2885.  
  2886. scripts['igra-prestoloff.cx'] = () => scriptLander(() => {
  2887. let nt = new nullTools();
  2888. /*jslint evil: true */ // yes, evil, I know
  2889. let _write = document.write.bind(document);
  2890. /*jslint evil: false */
  2891. nt.define(document, 'write', t => {
  2892. let id = t.match(/jwplayer\("(\w+)"\)/i);
  2893. if (id && id[1]) {
  2894. return _write(`<div id="${id[1]}"></div>${t}`);
  2895. } else {
  2896. return _write('');
  2897. }
  2898. });
  2899. });
  2900.  
  2901. scripts['imageban.ru'] = {
  2902. now: preventPopunders,
  2903. dom: () => win.addEventListener('unload', () => location.hash = 'x'+Math.random().toString(36).substr(2), true)
  2904. };
  2905.  
  2906. scripts['kinopoisk.ru'] = {
  2907. now: () => {
  2908. // set no-branding body style
  2909. createStyle('body:not(#id) { background: #d5d5d5 url(/images/noBrandBg.jpg) 50% 0 no-repeat !important }');
  2910. },
  2911. dom: () => {
  2912. (style => style ? style.parentNode.removeChild(style) : console.log('Unable to locate branding style.')
  2913. )(_de.querySelector('#branding-style'));
  2914. }
  2915. };
  2916.  
  2917. scripts['mail.ru'] = () => scriptLander(() => {
  2918. let nt = new nullTools();
  2919. // Trick to prevent mail.ru from removing 3rd-party styles
  2920. nt.define(Object.prototype, 'restoreVisibility', nt.func(null), false);
  2921. // Disable some of their counters
  2922. nt.define(win, 'rb_counter', nt.func(null, 'rb_counter'));
  2923. if (location.hostname !== 'e.mail.ru')
  2924. nt.define(win, 'createRadar', nt.func(nt.func(null, 'aRadar'), 'createRadar'));
  2925. else
  2926. nt.define(win, 'aRadar', nt.func(null, 'aRadar'));
  2927.  
  2928. // Disable page scrambler on mail.ru to let extensions easily block ads there
  2929. function defineLocator(root)
  2930. {
  2931. let _locator;
  2932. let fishnet = {
  2933. apply: (target, thisArg, args) => {
  2934. console.log(`locator.${target._name}(${JSON.stringify(args).slice(1,-1)})`);
  2935. return target.apply(thisArg, args);
  2936. }
  2937. };
  2938.  
  2939. function wrapLocator(locator)
  2940. {
  2941. if ('setup' in locator)
  2942. {
  2943. let _setup = locator.setup;
  2944. locator.setup = function(o)
  2945. {
  2946. if ('enable' in o)
  2947. {
  2948. o.enable = false;
  2949. console.log('Disable mimic mode.');
  2950. }
  2951. if ('links' in o)
  2952. {
  2953. o.links = [];
  2954. console.log('Call with empty list of sheets.');
  2955. }
  2956. return _setup.call(this, o);
  2957. };
  2958. locator.insertSheet = () => console.log('Ignore insertSheet.');
  2959. locator.wrap = () => console.log('Ignore wrap.');
  2960. }
  2961. try {
  2962. let names = [];
  2963. for (let name in locator)
  2964. if (locator[name] instanceof Function) {
  2965. locator[name]._name = name;
  2966. locator[name] = new Proxy(locator[name], fishnet);
  2967. names.push(name);
  2968. }
  2969. console.log(`[locator] wrapped properties: ${names.join(', ')}`);
  2970. } catch(e) {
  2971. console.log(e);
  2972. }
  2973. _locator = locator;
  2974. }
  2975.  
  2976. if ('locator' in root && root.locator)
  2977. {
  2978. console.log('Found existing "locator" object. :|');
  2979. _locator = root.locator;
  2980. wrapLocator(root.locator);
  2981. }
  2982.  
  2983. let loc_desc = Object.getOwnPropertyDescriptor(root, 'locator');
  2984. if (!loc_desc || loc_desc.set !== wrapLocator)
  2985. try {
  2986. Object.defineProperty(root, 'locator', {
  2987. set: wrapLocator,
  2988. get: () => _locator
  2989. });
  2990. } catch (err) {
  2991. console.log('Unable to redefine "locator" object!!!', err);
  2992. }
  2993. }
  2994.  
  2995. function defineDetector(mr)
  2996. {
  2997. let __ = mr._ || {};
  2998.  
  2999. if ('HONEYPOT' in __)
  3000. {
  3001. console.log('Disarming existing detector instance. :|', JSON.stringify(__));
  3002. nt.define(__, 'HONEYPOT', '.honeypot_fake_class_to_miss');
  3003. nt.define(__, 'STUCK_IN_POT', false);
  3004. }
  3005.  
  3006. __ = new Proxy(__, {
  3007. get: (t, p) => t[p],
  3008. set: (t, p, v) => {
  3009. console.log(`mr._.${p} =`, v);
  3010. if (['HONEYPOT', 'STUCK_IN_POT'].includes(p))
  3011. console.log('Not changed.');
  3012. t[p] = v; // setter in nt.define will prevent this when needed
  3013. return true;
  3014. }
  3015. });
  3016. Object.defineProperty(mr, '_', {
  3017. enumerable: true,
  3018. value: __
  3019. });
  3020. }
  3021.  
  3022. if (location.hostname === 'e.mail.ru')
  3023. defineLocator(win);
  3024. else {
  3025. try {
  3026. let _mr;
  3027. Object.defineProperty(win, 'mr', {
  3028. enumerable: true,
  3029. get: () => _mr,
  3030. set: (v) => {
  3031. if (v === _mr)
  3032. return true;
  3033. console.log('Trapped new "mr" object.');
  3034. defineLocator(v.mimic ? v.mimic : v);
  3035. defineDetector(v);
  3036. _mr = v;
  3037. }
  3038. });
  3039. if (!('mr' in win))
  3040. throw 'Wat!?';
  3041. } catch (e) {
  3042. console.log('Found existing "mr" object.', e instanceof TypeError ? '' : e);
  3043. defineLocator(win.mr);
  3044. defineDetector(win.mr);
  3045. }
  3046. }
  3047. }, nullTools);
  3048.  
  3049. scripts['megogo.net'] = {
  3050. now: () => {
  3051. let nt = new nullTools();
  3052. nt.define(win, 'adBlock', false);
  3053. nt.define(win, 'showAdBlockMessage', nt.func(null));
  3054. }
  3055. };
  3056.  
  3057. scripts['naruto-base.su'] = () => gardener('div[id^="entryID"],.block', /href="http.*?target="_blank"/i);
  3058.  
  3059. scripts['overclockers.ru'] = {
  3060. now: () => scriptLander(() => {
  3061. let _innerHTML = Object.getOwnPropertyDescriptor(Element.prototype, 'innerHTML');
  3062. let _set_innerHTML = _innerHTML.set;
  3063. _innerHTML.set = function() {
  3064. if (this === document.body) {
  3065. console.log('Anti-Adblock killed.');
  3066. return true;
  3067. }
  3068. _set_innerHTML.apply(this, arguments);
  3069. };
  3070. Object.defineProperty(Element.prototype, 'innerHTML', _innerHTML);
  3071. })
  3072. };
  3073. scripts['forums.overclockers.ru'] = {
  3074. now: () => {
  3075. createStyle('.needblock {position: fixed; left: -10000px}');
  3076. Object.defineProperty(win, 'adblck', {
  3077. get: () => 'no',
  3078. set: () => undefined,
  3079. enumerable: true
  3080. });
  3081. }
  3082. };
  3083.  
  3084. scripts['pb.wtf'] = {
  3085. other: ['piratbit.org', 'piratbit.ru'],
  3086. now: () => {
  3087. // line above topic content and images in the slider in the header
  3088. gardener(
  3089. 'a[href^="/exit/"], a[href^="/fxt/"], a[href$="=="]',
  3090. /img|Реклама|center/i,
  3091. { root: '.release-navbar,#page_content', observe: true, parent: 'div,tr' }
  3092. );
  3093. // ads in comments
  3094. gardener('img[data-name="PiraBo"]', /./i, {root:'#main_content .table', observe:true, parent:'tr'});
  3095. }
  3096. };
  3097.  
  3098. scripts['pikabu.ru'] = () => gardener('.story', /story__author[^>]+>ads</i, {root: '.inner_wrap', observe: true});
  3099.  
  3100. scripts['peka2.tv'] = () => {
  3101. let bodyClass = 'body--branding';
  3102. let checkNode = node => {
  3103. for (let className of node.classList)
  3104. if (className.includes('banner') || className === bodyClass) {
  3105. _removeAttribute.call(node, 'style');
  3106. node.classList.remove(className);
  3107. for (let attr of Array.from(node.attributes)) {
  3108. if (attr.name.startsWith('advert'))
  3109. _removeAttribute.call(node, attr.name);
  3110. }
  3111. }
  3112. };
  3113. (new MutationObserver(ms => {
  3114. let m, node;
  3115. for (m of ms) for (node of m.addedNodes)
  3116. if (node instanceof HTMLElement)
  3117. checkNode(node);
  3118. })).observe(_de, {childList: true, subtree: true});
  3119. (new MutationObserver(ms => {
  3120. for (let m of ms)
  3121. checkNode(m.target);
  3122. })).observe(_de, {attributes: true, subtree: true, attributeFilter: ['class']});
  3123. };
  3124.  
  3125. scripts['qrz.ru'] = {
  3126. now: () => {
  3127. let nt = new nullTools();
  3128. nt.define(win, 'ab', false);
  3129. nt.define(win, 'tryMessage', nt.func(null));
  3130. }
  3131. };
  3132.  
  3133. scripts['razlozhi.ru'] = {
  3134. now: () => {
  3135. for (let func of ['createShadowRoot', 'attachShadow'])
  3136. if (func in Element.prototype)
  3137. Element.prototype[func] = function(){ return this.cloneNode(); };
  3138. }
  3139. };
  3140.  
  3141. scripts['rbc.ru'] = {
  3142. dom: () => {
  3143. let _preventDefault = Event.prototype.preventDefault;
  3144. Event.prototype.preventDefault = function preventDefault()
  3145. {
  3146. let t = this.target;
  3147. if (t instanceof HTMLAnchorElement || t.closest('A'))
  3148. throw new Error('an.yandex redirect prevention');
  3149. return _preventDefault.call(this);
  3150. };
  3151.  
  3152. function cleaner(nodes)
  3153. {
  3154. for (let node of nodes)
  3155. {
  3156. if (!node.classList || !node.classList.contains('js-yandex-counter'))
  3157. continue;
  3158. node.classList.remove('js-yandex-counter');
  3159. node.removeAttribute('data-yandex-name');
  3160. node.removeAttribute('data-yandex-params');
  3161. }
  3162. }
  3163. cleaner(_de.querySelectorAll('.js-yandex-counter'));
  3164.  
  3165. (new MutationObserver(
  3166. ms => { for (let m of ms) cleaner(m.addedNodes); }
  3167. )).observe(_de, {childList: true, subtree: true});
  3168. }
  3169. };
  3170.  
  3171. scripts['rp5.ru'] = {
  3172. other: ['rp5.by', 'rp5.kz', 'rp5.ua'],
  3173. now: () => gardener('div[id][class]', /\?AdvertMgmt=|adsbygoogle/, { root: '#content-wrapper', log: true })
  3174. };
  3175.  
  3176. scripts['simpsonsua.com.ua'] = () => {
  3177. let nt = new nullTools();
  3178. nt.define(win, 'need_warning', 0);
  3179. nt.define(win, 'show_warning_js', nt.func());
  3180. };
  3181.  
  3182. scripts['spaces.ru'] = () => {
  3183. gardener('div:not(.f-c_fll) > a[href*="spaces.ru/?Cl="]', /./, { parent: 'div' });
  3184. gardener('.js-banner_rotator', /./, { parent: '.widgets-group' });
  3185. };
  3186.  
  3187. scripts['spam-club.blogspot.co.uk'] = () => {
  3188. let _clientHeight = Object.getOwnPropertyDescriptor(Element.prototype, 'clientHeight'),
  3189. _clientWidth = Object.getOwnPropertyDescriptor(Element.prototype, 'clientWidth');
  3190. let wrapGetter = (getter) => {
  3191. let _getter = getter;
  3192. return function()
  3193. {
  3194. let _size = _getter.apply(this, arguments);
  3195. return _size ? _size : 1;
  3196. };
  3197. };
  3198. _clientHeight.get = wrapGetter(_clientHeight.get);
  3199. _clientWidth.get = wrapGetter(_clientWidth.get);
  3200. Object.defineProperty(Element.prototype, 'clientHeight', _clientHeight);
  3201. Object.defineProperty(Element.prototype, 'clientWidth', _clientWidth);
  3202. let _onload = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'onload'),
  3203. _set_onload = _onload.set;
  3204. _onload.set = function()
  3205. {
  3206. if (this instanceof HTMLImageElement)
  3207. return true;
  3208. _set_onload.apply(this, arguments);
  3209. };
  3210. Object.defineProperty(HTMLElement.prototype, 'onload', _onload);
  3211. };
  3212.  
  3213. scripts['sport-express.ru'] = () => gardener('.js-relap__item',/>Реклама\s+<\//, {root:'.container', observe: true});
  3214.  
  3215. scripts['sports.ru'] = {
  3216. now: () => {
  3217. gardener('.aside-news-list__item', /aside-news-list__advert/i, {root:'.columns-layout__left', observe: true});
  3218. gardener('.material-list__item', /Реклама/i, {root:'.columns-layout', observe: true});
  3219. // extra functionality: shows/hides panel at the top depending on scroll direction
  3220. createStyle([
  3221. '.user-panel__fixed { transition: top 0.2s ease-in-out!important; }',
  3222. '.user-panel-up { top: -40px!important }'
  3223. ], {id: 'userPanelSlide'}, false);
  3224. },
  3225. dom: () => {
  3226. (function lookForPanel()
  3227. {
  3228. let panel = document.querySelector('.user-panel__fixed');
  3229. if (!panel)
  3230. setTimeout(lookForPanel, 100);
  3231. else
  3232. window.addEventListener(
  3233. 'wheel', function(e)
  3234. {
  3235. if (e.deltaY > 0 && !panel.classList.contains('user-panel-up'))
  3236. panel.classList.add('user-panel-up');
  3237. else if (e.deltaY < 0 && panel.classList.contains('user-panel-up'))
  3238. panel.classList.remove('user-panel-up');
  3239. }, false
  3240. );
  3241. })();
  3242. }
  3243. };
  3244.  
  3245. scripts['stealthz.ru'] = {
  3246. dom: () => {
  3247. // skip timeout
  3248. let $ = document.querySelector.bind(document);
  3249. let [timer_1, timer_2] = [$('#timer_1'), $('#timer_2')];
  3250. if (!timer_1 || !timer_2)
  3251. return;
  3252. timer_1.style.display = 'none';
  3253. timer_2.style.display = 'block';
  3254. }
  3255. };
  3256.  
  3257. scripts['yap.ru'] = {
  3258. other: ['yaplakal.com'],
  3259. now: () => {
  3260. gardener('form > table[id^="p_row_"]:nth-of-type(2)', /member1438|Administration/);
  3261. gardener('.icon-comments', /member1438|Administration|\/go\/\?http/, {parent:'tr', siblings:-2});
  3262. }
  3263. };
  3264.  
  3265. scripts['rambler.ru'] = {
  3266. other: ['championat.com','gazeta.ru','media.eagleplatform.com','lenta.ru', 'quto.ru'],
  3267. now: () => scriptLander(() => {
  3268. // Prevent autoplay
  3269. if (!('EaglePlayer' in win)) {
  3270. let _EaglePlayer = void 0;
  3271. Object.defineProperty(win, 'EaglePlayer', {
  3272. enumerable: true,
  3273. get: x => _EaglePlayer,
  3274. set: x => {
  3275. if (x === _EaglePlayer)
  3276. return true;
  3277. _EaglePlayer = x;
  3278. let _init = void 0;
  3279. Object.defineProperty(_EaglePlayer.prototype, 'init', {
  3280. enumerable: true,
  3281. set: x => _init = x,
  3282. get: function() {
  3283. let _self = this;
  3284. if (_self.options) {
  3285. Object.defineProperty(this.options, 'autoplay', {
  3286. enumerable: true,
  3287. get: x => false,
  3288. set: x => null
  3289. });
  3290. }
  3291. if (_self.options && _self.options.el && inIFrame) {
  3292. let addListener = (player) => {
  3293. console.log('Attached autostop');
  3294. player.addEventListener('canplay', e => {
  3295. e.target.play = () => console.log('Applied autostop.');
  3296. setTimeout(player => {
  3297. delete player.play;
  3298. console.log('Detached autostop');
  3299. }, 1500, e.target);
  3300. }, false);
  3301. };
  3302. (new MutationObserver(ms => {
  3303. let m, node;
  3304. for (m of ms) for (node of m.addedNodes)
  3305. if (node instanceof HTMLVideoElement)
  3306. addListener(node);
  3307. })).observe(this.options.el, { childList: true, subtree: true });
  3308. }
  3309. return _init;
  3310. }
  3311. });
  3312. }
  3313. });
  3314. let _setAttribute = Element.prototype.setAttribute;
  3315. let isAutoplay = /^autoplay$/i;
  3316. Element.prototype.setAttribute = function setAttribute(name)
  3317. {
  3318. if (!this._stopped && isAutoplay.test(name))
  3319. {
  3320. console.log('Prevented assigning autoplay attribute.');
  3321. return null;
  3322. }
  3323. return _setAttribute.apply(this, arguments);
  3324. };
  3325. } else if (inIFrame) {
  3326. let _setAttribute = Element.prototype.setAttribute;
  3327. let isAutoplay = /^autoplay$/i;
  3328. Element.prototype.setAttribute = function setAttribute(name)
  3329. {
  3330. if (!this._stopped && isAutoplay.test(name))
  3331. {
  3332. console.log('Prevented assigning autoplay attribute.');
  3333. this._stopped = true;
  3334. this.play = () => {
  3335. console.log('Prevented attempt to force-start playback.');
  3336. delete this.play;
  3337. };
  3338. return null;
  3339. }
  3340. return _setAttribute.apply(this, arguments);
  3341. };
  3342. }
  3343. if (location.hostname.endsWith('.media.eagleplatform.com'))
  3344. return;
  3345. let CSSRuleProto = 'cssText' in CSSRule.prototype ? CSSRule.prototype : CSSStyleRule.prototype;
  3346. let _cssText = Object.getOwnPropertyDescriptor(CSSRuleProto, 'cssText');
  3347. let _cssText_get = _cssText.get;
  3348. _cssText.configurable = false;
  3349. _cssText.get = function()
  3350. {
  3351. let cssText = _cssText_get.call(this);
  3352. if (cssText.includes('content:'))
  3353. {
  3354. console.log('Blocked access to suspicious cssText:', cssText.slice(0,60), '\u2026', cssText.length);
  3355. return null;
  3356. }
  3357. return cssText;
  3358. };
  3359. Object.defineProperty(CSSRuleProto, 'cssText', _cssText);
  3360. // fake global Adf object
  3361. let nt = new nullTools();
  3362. let Adf_banner = {};
  3363. [
  3364. 'reloadssp', 'sspScroll',
  3365. 'sspRich', 'ssp'
  3366. ].map(name => Adf_banner[name] = nt.proxy(() => new Promise((r,j) => r({status: true}))));
  3367. nt.define(win, 'Adf', nt.proxy({
  3368. banner: nt.proxy(Adf_banner)
  3369. }));
  3370. // extra script to remove partner news on gazeta.ru
  3371. if (!location.hostname.includes('gazeta.ru'))
  3372. return;
  3373. (new MutationObserver(
  3374. (ms) => {
  3375. let m, node, header;
  3376. for (m of ms) for (node of m.addedNodes)
  3377. if (node instanceof HTMLDivElement && node.matches('.sausage'))
  3378. {
  3379. header = node.querySelector('.sausage-header');
  3380. if (header && /новости\s+партн[её]ров/i.test(header.textContent))
  3381. node.style.display = 'none';
  3382. }
  3383. }
  3384. )).observe(document.documentElement, { childList:true, subtree: true });
  3385. }, `let inIFrame = ${inIFrame}`, nullTools)
  3386. };
  3387.  
  3388. scripts['reactor.cc'] = {
  3389. other: ['joyreactor.cc', 'pornreactor.cc'],
  3390. now: () => {
  3391. selectiveEval();
  3392. scriptLander(() => {
  3393. let nt = new nullTools();
  3394. win.open = (function(){ throw new Error('Redirect prevention.'); }).bind(window);
  3395. nt.define(win, 'Worker', function(){});
  3396. nt.define(win, 'JRCH', win.CoinHive);
  3397. }, nullTools);
  3398. },
  3399. click: function(e)
  3400. {
  3401. let node = e.target;
  3402. if (node.nodeType === Node.ELEMENT_NODE &&
  3403. node.style.position === 'absolute' &&
  3404. node.style.zIndex > 0)
  3405. node.parentNode.removeChild(node);
  3406. },
  3407. dom: function()
  3408. {
  3409. let words = new RegExp(
  3410. 'блокировщик рекламы'
  3411. .split('')
  3412. .map(function(e){return e+'[\u200b\u200c\u200d]*';})
  3413. .join('')
  3414. .replace(' ', '\\s*')
  3415. .replace(/[аоре]/g, function(e){return ['[аa]','[оo]','[рp]','[еe]']['аоре'.indexOf(e)];}),
  3416. 'i'),
  3417. can;
  3418. function deeper(spider)
  3419. {
  3420. let c, l, n;
  3421. if (words.test(spider.innerText))
  3422. {
  3423. if (spider.nodeType === Node.TEXT_NODE)
  3424. return true;
  3425. c = spider.childNodes;
  3426. l = c.length;
  3427. n = 0;
  3428. while(l--)
  3429. if (deeper(c[l]), can)
  3430. n++;
  3431. if (n > 0 && n === c.length && spider.offsetHeight < 750)
  3432. can.push(spider);
  3433. return false;
  3434. }
  3435. return true;
  3436. }
  3437. function probe()
  3438. {
  3439. if (words.test(document.body.innerText))
  3440. {
  3441. can = [];
  3442. deeper(document.body);
  3443. let i = can.length, spider;
  3444. while(i--) {
  3445. spider = can[i];
  3446. if (spider.offsetHeight > 10 && spider.offsetHeight < 750)
  3447. _setAttribute.call(spider, 'style', 'background:none!important');
  3448. }
  3449. }
  3450. }
  3451. (new MutationObserver(probe))
  3452. .observe(document, { childList:true, subtree:true });
  3453. }
  3454. };
  3455.  
  3456. scripts['auto.ru'] = () => {
  3457. let words = /Реклама|Яндекс.Директ|yandex_ad_/;
  3458. let userAdsListAds = (
  3459. '.listing-list > .listing-item,'+
  3460. '.listing-item_type_fixed.listing-item'
  3461. );
  3462. let catalogAds = (
  3463. 'div[class*="layout_catalog-inline"],'+
  3464. 'div[class$="layout_horizontal"]'
  3465. );
  3466. let otherAds = (
  3467. '.advt_auto,'+
  3468. '.sidebar-block,'+
  3469. '.pager-listing + div[class],'+
  3470. '.card > div[class][style],'+
  3471. '.sidebar > div[class],'+
  3472. '.main-page__section + div[class],'+
  3473. '.listing > tbody'
  3474. );
  3475. gardener(userAdsListAds, words, {root:'.listing-wrap', observe:true});
  3476. gardener(catalogAds, words, {root:'.catalog__page,.content__wrapper', observe:true});
  3477. gardener(otherAds, words);
  3478. };
  3479.  
  3480. scripts['rsload.net'] = {
  3481. load: () => {
  3482. let dis = document.querySelector('label[class*="cb-disable"]');
  3483. if (dis)
  3484. dis.click();
  3485. },
  3486. click: () => {
  3487. let t = e.target;
  3488. if (t && t.href && (/:\/\/\d+\.\d+\.\d+\.\d+\//.test(t.href)))
  3489. t.href = t.href.replace('://','://rsload.net:rsload.net@');
  3490. }
  3491. };
  3492.  
  3493. let domain;
  3494. // add alternative domain names if present and wrap functions into objects
  3495. for (let name in scripts)
  3496. {
  3497. if (scripts[name] instanceof Function)
  3498. scripts[name] = { now: scripts[name] };
  3499. for (domain of (scripts[name].other||[]))
  3500. {
  3501. if (domain in scripts)
  3502. console.log('Error in scripts list. Script for', name, 'replaced script for', domain);
  3503. scripts[domain] = scripts[name];
  3504. }
  3505. delete scripts[name].other;
  3506. }
  3507. // look for current domain in the list and run appropriate code
  3508. domain = document.domain;
  3509. while (domain.indexOf('.') > -1)
  3510. {
  3511. if (domain in scripts) for (let when in scripts[domain])
  3512. switch(when)
  3513. {
  3514. case 'now':
  3515. scripts[domain][when]();
  3516. break;
  3517. case 'dom':
  3518. document.addEventListener('DOMContentLoaded', scripts[domain][when], false);
  3519. break;
  3520. default:
  3521. document.addEventListener (when, scripts[domain][when], false);
  3522. }
  3523. domain = domain.slice(domain.indexOf('.') + 1);
  3524. }
  3525. })();