RU AdList JS Fixes

try to take over the world!

当前为 2017-12-26 提交的版本,查看 最新版本

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