RU AdList JS Fixes

try to take over the world!

目前为 2017-10-06 提交的版本,查看 最新版本

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