Greasy Fork 还支持 简体中文。

RU AdList JS Fixes

try to take over the world!

目前為 2018-01-14 提交的版本,檢視 最新版本

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