RU AdList JS Fixes

try to take over the world!

目前為 2017-10-12 提交的版本,檢視 最新版本

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