RU AdList JS Fixes

try to take over the world!

当前为 2017-10-04 提交的版本,查看 最新版本

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