RU AdList JS Fixes

try to take over the world!

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

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址