RU AdList JS Fixes

try to take over the world!

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

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