RU AdList JS Fixes

try to take over the world!

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

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