Webpage mask

A customizable mask layer above any webpage. You can use it as a privacy mask, a screensaver, a nightmode filter... and so on.

  1. // ==UserScript==
  2. // @name Webpage mask
  3. // @name:zh-CN 网页遮罩层
  4. // @name:en Webpage mask
  5. // @namespace https://greatest.deepsurf.us/users/667968-pyudng
  6. // @version 0.4.2
  7. // @description A customizable mask layer above any webpage. You can use it as a privacy mask, a screensaver, a nightmode filter... and so on.
  8. // @description:zh-CN 在网页上方添加一个可以自定义的遮罩层。可以用来遮挡隐私内容,或者用作屏保,又或是用来设置护眼模式... 等等等等
  9. // @description:en A customizable mask layer above any webpage. You can use it as a privacy mask, a screensaver, a nightmode filter... and so on.
  10. // @author PY-DNG
  11. // @license MIT
  12. // @match http*://*/*
  13. // @require https://update.greatest.deepsurf.us/scripts/456034/1532680/Basic%20Functions%20%28For%20userscripts%29.js
  14. // @grant GM_registerMenuCommand
  15. // @grant GM_getValue
  16. // @grant GM_setValue
  17. // @grant GM_addElement
  18. // @run-at document-start
  19. // ==/UserScript==
  20.  
  21. /* eslint-disable no-multi-spaces */
  22. /* eslint-disable no-return-assign */
  23.  
  24. /* global LogLevel DoLog Err $ $All $CrE $AEL $$CrE addStyle detectDom destroyEvent copyProp copyProps parseArgs escJsStr replaceText getUrlArgv dl_browser dl_GM AsyncManager queueTask FunctionLoader loadFuncs require isLoaded */
  25.  
  26. /* Important note: this script is for convenience, but is NOT a security tool.
  27. ANYONE with basic web programming knowledge CAN EASYILY UNLOCK/UNCENSOR/REMOVE MASK
  28. without permission/password AND EVEN YOU CANNOT KNOW IT */
  29.  
  30. (function __MAIN__() {
  31. 'use strict';
  32.  
  33. const CONST = {
  34. TextAllLang: {
  35. DEFAULT: 'en',
  36. 'zh-CN': {
  37. CompatAlert: '用户脚本 [网页遮罩层] 提示:\n(本提示仅展示一次)本脚本推荐使用最新版Tampermonkey运行,如果使用旧版Tampermonkey或其他脚本管理器可能导致兼容性问题,请注意。',
  38. Mask: '开启',
  39. Unmask: '关闭',
  40. EnableAutomask: '为此网站开启自动遮罩',
  41. DisableAutomask: '关闭此网站的自动遮罩',
  42. SetIDLETime: '设置自动遮罩触发时间',
  43. PromptIDLETime: '每当 N 秒无操作后,将为网站自动开启遮罩\n您希望 N 为:',
  44. TamperorilyDisable: '暂时禁用遮罩层',
  45. TamperorilyDisabled: '已暂时禁用遮罩层:当前网页在下一次刷新前,都不会展示遮罩层',
  46. CustomUserstyle: '自定义遮罩层样式',
  47. PromptUserstyle: '您可以在此彻底地自定义遮罩层\n如果您不确定怎么写或者不小心写错了,留空并点击确定即可重置为默认值\n\n格式:\ncss:CSS值 - 设定自定义CSS样式\nimg:网址 - 在遮罩层上全屏显示网址对应的图片\njs:代码 - 执行自定义js代码,您可以使用js:debugger测试运行环境、调试您的代码',
  48. IDLETimeInvalid: '您的输入不正确:只能输入大于等于零的整数或小数'
  49. },
  50. 'en': {
  51. CompatAlert: '(This is a one-time alert)\nFrom userscript [Privacy mask]:\nThis userscript is designed for latest versions of Tampermonkey, working with old versions or other script manager may encounter bugs.',
  52. Mask: 'Show mask',
  53. Unmask: 'Hide mask',
  54. EnableAutomask: 'Enable auto-mask for this site',
  55. DisableAutomask: 'Disable auto-mask for this site',
  56. SetIDLETime: 'Configure auto-mask time',
  57. PromptIDLETime: 'Mask will be shown after the webpage has been idle for N second(s).\n You can set that N here:',
  58. TamperorilyDisable: 'Tamperorily disable mask',
  59. TamperorilyDisabled: 'Mask tamperorily disabled: mask will not be shown in current webpage before refreshing the webpage',
  60. CustomUserstyle: 'Custom auto-mask style',
  61. PromptUserstyle: 'You can custom the content and style of the mask here\nIf you\'re not sure how to compose styles, leave it blank to set back to default.\n\nStyle format:\ncss:CSS - Apply custom css stylesheet\nimg:url - Display custom image by fullscreen\njs:code - Execute custom javascript when mask created. You can use "js:debugger" to test your code an the environment.',
  62. IDLETimeInvalid: 'Invalid input: positive numbers only'
  63. }
  64. },
  65. Style: {
  66. BuiltinStyle: '#mask {position: fixed; top: 0; left: 0; right: 100vw; bottom: 100vh; width: 100vw; height: 100vh; border: 0; margin: 0; padding: 0; background: transparent; z-index: 2147483647; display: none} #mask.show {display: block;}',
  67. DefaultUserstyle: 'css:#mask {backdrop-filter: blur(30px);}'
  68. }
  69. };
  70.  
  71. // Init language
  72. const i18n = Object.keys(CONST.TextAllLang).includes(navigator.language) ? navigator.language : CONST.TextAllLang.DEFAULT;
  73. CONST.Text = CONST.TextAllLang[i18n];
  74.  
  75. loadFuncs([{
  76. id: 'mask',
  77. desc: 'Core: create mask DOM, provide basic mask api',
  78. detectDom: 'body',
  79. dependencies: 'utils',
  80. func: () => {
  81. const utils = require('utils');
  82. const return_obj = new EventTarget();
  83.  
  84. // Make mask
  85. const mask_container = $$CrE({
  86. tagName: 'div',
  87. styles: { all: 'initial' }
  88. });
  89. const mask = $$CrE({
  90. tagName: 'div',
  91. props: { id: 'mask' }
  92. });
  93. const shadow = mask_container.attachShadow({ mode: unsafeWindow.isPY_DNG ? 'open' : 'closed' });
  94. shadow.appendChild(mask);
  95. document.body.after(mask_container);
  96.  
  97. // Styles
  98. const style = addStyle(shadow, CONST.Style.BuiltinStyle, 'mask-builtin-style');
  99. applyUserstyle();
  100.  
  101. ['mouseup', 'keyup', 'dragenter'].forEach(evtname => utils.$AEL(unsafeWindow, evtname, e => hide()));
  102.  
  103. const return_props = {
  104. mask_container, element: mask, shadow, style, show, hide,
  105. get showing() { return showing(); },
  106. set showing(v) { v ? show() : hide() },
  107. get userstyle() { return getUserstyle() },
  108. set userstyle(v) { return setUserstyle(v) }
  109. };
  110. utils.copyPropDescs(return_props, return_obj);
  111. return return_obj;
  112.  
  113. function show() {
  114. const defaultNotPrevented = return_obj.dispatchEvent(new Event('show', { cancelable: true }));
  115. defaultNotPrevented && mask.classList.add('show');
  116. }
  117.  
  118. function hide() {
  119. const defaultNotPrevented = return_obj.dispatchEvent(new Event('hide', { cancelable: true }));
  120. defaultNotPrevented && mask.classList.remove('show');
  121. }
  122.  
  123. function showing() {
  124. return mask.classList.contains('show');
  125. }
  126.  
  127. function getUserstyle() {
  128. return GM_getValue('userstyle', CONST.Style.DefaultUserstyle);
  129. }
  130.  
  131. function setUserstyle(val) {
  132. const defaultNotPrevented = return_obj.dispatchEvent(new Event('restyle', { cancelable: true }));
  133. if (defaultNotPrevented) {
  134. applyUserstyle(val);
  135. GM_setValue('userstyle', val);
  136. }
  137. }
  138.  
  139. function applyUserstyle(val) {
  140. if (!val) { val = getUserstyle() }
  141. if (!val.includes(':')) { Err('mask.applyUserStyle: type not found') }
  142. const type = val.substring(0, val.indexOf(':')).toLowerCase();
  143. const value = val.substring(val.indexOf(':') + 1).trim();
  144. switch (type) {
  145. case 'css':
  146. GM_addElement(shadow, 'style', { textContent: value, style: 'user' });
  147. utils.$AEL(return_obj, 'restyle', e => $(shadow, 'style[style="user"]').remove(), { once: true });
  148. break;
  149. case 'js':
  150. case 'javascript':
  151. utils.exec(value, { require, CONST });
  152. break;
  153. case 'img':
  154. case 'image': {
  155. addImage(value);
  156. break;
  157.  
  158. function addImage(src, remaining_retry=3) {
  159. const img = GM_addElement(mask, 'img', {
  160. src: value,
  161. style: 'width: 100vw; height: 100vh; border: 0; padding: 0; margin: 0;',
  162. crossorigin: 'anonymous'
  163. }) ?? $(mask, 'img');
  164. const controller = new AbortController();
  165. utils.$AEL(img, 'error', e => {
  166. if (remaining_retry-- > 0) {
  167. DoLog(LogLevel.Warning, `Mask image load error, retrying...\n(remaining ${remaining_retry} retries)`);
  168. controller.abort();
  169. img.remove();
  170. addImage(src, remaining_retry);
  171. } else {
  172. DoLog(LogLevel.Error, `Mask image load error (after maximum retries)\nTry reloading the page or changing an image\nImage url: ${src}`);
  173. }
  174. }, { once: true });
  175. utils.$AEL(return_obj, 'restyle', e => img.remove(), {
  176. once: true,
  177. signal: controller.signal
  178. });
  179. }
  180. }
  181. default:
  182. Error(`mask.applyUserStyle: Unknown type: ${type}`);
  183. }
  184. }
  185. }
  186. }, {
  187. id: 'control',
  188. desc: 'Provide mask control ui to user',
  189. dependencies: ['utils', 'mask'],
  190. func: () => {
  191. const utils = require('utils');
  192. const mask = require('mask');
  193.  
  194. // Switch menu builder
  195. const buildMenu = (text_getter, callback, id=null) => GM_registerMenuCommand(text_getter(), callback, id !== null ? { id } : {});
  196.  
  197. // Enable/Disable switch
  198. const show_text_getter = () => CONST.Text[mask.showing ? 'Unmask' : 'Mask'];
  199. const show_menu_onclick = e => mask.showing = !mask.showing;
  200. const buildShowMenu = (id = null) => buildMenu(show_text_getter, show_menu_onclick, id);
  201. const id = buildShowMenu();
  202. utils.$AEL(mask, 'show', e => setTimeout(() => buildShowMenu(id)));
  203. utils.$AEL(mask, 'hide', e => setTimeout(() => buildShowMenu(id)));
  204.  
  205. // Tamperorily disable
  206. GM_registerMenuCommand(CONST.Text.TamperorilyDisable, e => {
  207. mask.hide();
  208. utils.$AEL(mask, 'show', e => e.preventDefault());
  209. DoLog(LogLevel.Success, CONST.Text.TamperorilyDisabled);
  210. setTimeout(() => alert(CONST.Text.TamperorilyDisabled));
  211. });
  212.  
  213. // Custom user style
  214. GM_registerMenuCommand(CONST.Text.CustomUserstyle, e => {
  215. let style = prompt(CONST.Text.PromptUserstyle, mask.userstyle);
  216. if (style === null) { return; }
  217. if (style === '') { style = CONST.Style.DefaultUserstyle }
  218. // Here should add an style valid check
  219. mask.userstyle = style;
  220. });
  221.  
  222. return { id };
  223. }
  224. }, {
  225. id: 'automask',
  226. desc: 'extension: auto-mask after certain idle time',
  227. detectDom: 'body',
  228. dependencies: ['mask', 'utils'],
  229. func: () => {
  230. const utils = require('utils');
  231. const mask = require('mask');
  232. const id = GM_registerMenuCommand(
  233. isAutomaskEnabled() ? CONST.Text.DisableAutomask : CONST.Text.EnableAutomask,
  234. function onClick(e) {
  235. isAutomaskEnabled() ? disable() : enable();
  236. GM_registerMenuCommand(
  237. isAutomaskEnabled() ? CONST.Text.DisableAutomask : CONST.Text.EnableAutomask,
  238. onClick, { id }
  239. );
  240. isAutomaskEnabled() && check_idle();
  241. }
  242. );
  243. GM_registerMenuCommand(CONST.Text.SetIDLETime, e => {
  244. const config = getConfig();
  245. const time = prompt(CONST.Text.PromptIDLETime, config.idle_time);
  246. if (time === null) { return; }
  247. if (!/^(\d+\.)?\d+$/.test(time)) { alert(CONST.Text.IDLETimeInvalid); return; }
  248. config.idle_time = +time;
  249. setConfig(config);
  250. });
  251.  
  252. // Auto-mask when idle
  253. let last_refreshed = Date.now();
  254. const cancel_idle = () => {
  255. // Iframe events won't bubble into parent window, so manually tell top window to also cancel_idle
  256. const in_iframe = unsafeWindow !== unsafeWindow.top;
  257. in_iframe && utils.postMessage(unsafeWindow.top, 'iframe_cancel_idle');
  258. // Refresh time record
  259. last_refreshed = Date.now();
  260. };
  261. ['mousemove', 'mousedown', 'mouseup', 'wheel', 'keydown', 'keyup'].forEach(evt_name =>
  262. utils.$AEL(unsafeWindow, evt_name, e => cancel_idle(), { capture: true }));
  263. utils.recieveMessage('iframe_cancel_idle', e => cancel_idle());
  264. const check_idle = () => {
  265. const config = getConfig();
  266. const time_left = config.idle_time * 1000 - (Date.now() - last_refreshed);
  267. if (time_left <= 0) {
  268. isAutomaskEnabled() && !mask.showing && mask.show();
  269. utils.$AEL(mask, 'hide', e => {
  270. cancel_idle();
  271. check_idle();
  272. }, { once: true });
  273. } else {
  274. setTimeout(check_idle, time_left);
  275. }
  276. }
  277. check_idle();
  278.  
  279. return {
  280. id, enable, disable,
  281. get enabled() { return isAutomaskEnabled(); }
  282. };
  283.  
  284. function getConfig() {
  285. return GM_getValue('automask', {
  286. sites: [],
  287. idle_time: 30
  288. });
  289. }
  290.  
  291. function setConfig(val) {
  292. return GM_setValue('automask', val);
  293. }
  294.  
  295. function isAutomaskEnabled() {
  296. return getConfig().sites.includes(location.host);
  297. }
  298.  
  299. function enable() {
  300. if (isAutomaskEnabled()) { return; }
  301. const config = getConfig();
  302. config.sites.push(location.host);
  303. setConfig(config);
  304. }
  305.  
  306. function disable() {
  307. if (!isAutomaskEnabled()) { return; }
  308. const config = getConfig();
  309. config.sites.splice(config.sites.indexOf(location.host), 1);
  310. setConfig(config);
  311. }
  312. }
  313. }, {
  314. id: 'utils',
  315. desc: 'helper functions',
  316. func: () => {
  317. function GM_hasVersion(version) {
  318. return hasVersion(GM_info?.version || '0', version);
  319.  
  320. function hasVersion(ver1, ver2) {
  321. return compareVersions(ver1.toString(), ver2.toString()) >= 0;
  322.  
  323. // https://greatest.deepsurf.us/app/javascript/versioncheck.js
  324. // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/version/format
  325. function compareVersions(a, b) {
  326. if (a == b) {
  327. return 0;
  328. }
  329. let aParts = a.split('.');
  330. let bParts = b.split('.');
  331. for (let i = 0; i < aParts.length; i++) {
  332. let result = compareVersionPart(aParts[i], bParts[i]);
  333. if (result != 0) {
  334. return result;
  335. }
  336. }
  337. // If all of a's parts are the same as b's parts, but b has additional parts, b is greater.
  338. if (bParts.length > aParts.length) {
  339. return -1;
  340. }
  341. return 0;
  342. }
  343.  
  344. function compareVersionPart(partA, partB) {
  345. let partAParts = parseVersionPart(partA);
  346. let partBParts = parseVersionPart(partB);
  347. for (let i = 0; i < partAParts.length; i++) {
  348. // "A string-part that exists is always less than a string-part that doesn't exist"
  349. if (partAParts[i].length > 0 && partBParts[i].length == 0) {
  350. return -1;
  351. }
  352. if (partAParts[i].length == 0 && partBParts[i].length > 0) {
  353. return 1;
  354. }
  355. if (partAParts[i] > partBParts[i]) {
  356. return 1;
  357. }
  358. if (partAParts[i] < partBParts[i]) {
  359. return -1;
  360. }
  361. }
  362. return 0;
  363. }
  364.  
  365. // It goes number, string, number, string. If it doesn't exist, then
  366. // 0 for numbers, empty string for strings.
  367. function parseVersionPart(part) {
  368. if (!part) {
  369. return [0, "", 0, ""];
  370. }
  371. let partParts = /([0-9]*)([^0-9]*)([0-9]*)([^0-9]*)/.exec(part)
  372. return [
  373. partParts[1] ? parseInt(partParts[1]) : 0,
  374. partParts[2],
  375. partParts[3] ? parseInt(partParts[3]) : 0,
  376. partParts[4]
  377. ];
  378. }
  379. }
  380. }
  381.  
  382. function copyPropDescs(from, to) {
  383. Object.defineProperties(to, Object.getOwnPropertyDescriptors(from));
  384. }
  385.  
  386. function randint(min, max) {
  387. return Math.random() * (max - min) + min;
  388. }
  389.  
  390. function randstr(len) {
  391. const letters = [...Array(26).keys()].map( i => String.fromCharCode('a'.charCodeAt(0) + i) );
  392. let str = '';
  393. for (let i = 0; i < len; i++) {
  394. str += letters.at(randint(0, 25));
  395. }
  396. return str;
  397. }
  398.  
  399. /**
  400. * execute js code in a global function closure and try to bypass CSP rules
  401. * { name: 'John', number: 123456 } will be executed by (function(name, number) { code }) ('John', 123456);
  402. *
  403. * @param {string} code
  404. * @param {Object} args
  405. */
  406. function exec(code, args) {
  407. // Parse args
  408. const arg_names = Object.keys(args);
  409. const arg_vals = arg_names.map(name => args[name]);
  410. // Construct middle code and middle obj
  411. const id = randstr(16);
  412. const middle_obj = unsafeWindow[id] = { id, arg_vals, url: null };
  413. const middle_code_parts = {
  414. single_instance: [
  415. '// Run code only once',
  416. `if (!window.hasOwnProperty('${id}')) { return; }`
  417. ].join('\n'),
  418. cleaner: [
  419. '// Do some cleaning first',
  420. `const middle_obj = window.${id};`,
  421. `delete window.${id};`,
  422. `URL.revokeObjectURL(middle_obj.url);`,
  423. `document.querySelector('#${id}')?.remove();`
  424. ].join('\n'),
  425. executer: [
  426. '// Execute user code',
  427. `(function(${arg_names.join(', ')}, middle_obj) {`,
  428. code,
  429. `}).call(null, ...middle_obj.arg_vals, undefined);`
  430. ].join('\n'),
  431. }
  432. const middle_code = `(function() {\n${Object.values(middle_code_parts).join('\n\n')}\n}) ();`;
  433. const blob = new Blob([middle_code], { type: 'application/javascript' });
  434. const url = middle_obj.url = URL.createObjectURL(blob);
  435. // Create and execute <script>
  436. GM_addElement(document.head, 'script', { src: url, id });
  437. GM_addElement(document.head, 'script', { textContent: middle_code, id });
  438. }
  439.  
  440. /**
  441. * Some website (like icourse163.com, dolmods.com, etc.) hooked addEventListener,\
  442. * so calling target.addEventListener has no effect.
  443. * this function get a "pure" addEventListener from new iframe, and make use of it
  444. */
  445. function $AEL(target, ...args) {
  446. if (!$AEL.id_prop) {
  447. $AEL.id_prop = randstr(16);
  448. $AEL.id_val = randstr(16);
  449. GM_addElement(document.body, 'iframe', {
  450. srcdoc: '<html></html>',
  451. style: [
  452. 'border: 0',
  453. 'padding: 0',
  454. 'margin: 0',
  455. 'width: 0',
  456. 'height: 0',
  457. 'display: block',
  458. 'visibility: visible'
  459. ].concat('').join(' !important; '),
  460. [$AEL.id_prop]: $AEL.id_val,
  461. });
  462. }
  463. try {
  464. const ifr = $(`[${$AEL.id_prop}=${$AEL.id_val}]`);
  465. const AEL = ifr.contentWindow.EventTarget.prototype.addEventListener;
  466. return AEL.call(target, ...args);
  467. } catch (e) {
  468. if (!$(`[${$AEL.id_prop}=${$AEL.id_val}]`)) {
  469. DoLog(LogLevel.Warning, 'GM_addElement is not working properly: added iframe not found\nUsing normal addEventListener instead');
  470. } else {
  471. DoLog(LogLevel.Warning, 'Unknown error occured\nUsing normal addEventListener instead')
  472. }
  473. return window.EventTarget.prototype.addEventListener.call(target, ...args);
  474. }
  475. }
  476.  
  477. const [postMessage, recieveMessage] = (function() {
  478. // Check and init security key
  479. let securityKey = GM_getValue('Message-Security-Key');
  480. if (!securityKey) {
  481. securityKey = { prop: randstr(8), value: randstr(16) };
  482. GM_setValue('Message-Security-Key', securityKey);
  483. }
  484.  
  485. /**
  486. * post a message to target window using window.postMessage
  487. * name, data will be formed as an object in format of { name, data, securityKeyProp: securityKeyVal }
  488. * securityKey will be randomly generated with first initialization
  489. * and saved with GM_setValue('Message-Security-Key', { prop, value })
  490. *
  491. * @param {string} name - type of this message
  492. * @param {*} [data] - data of this message
  493. */
  494. function postMessage(targetWindow, name, data=null) {
  495. const securityKeyProp = securityKey.prop;
  496. const securityKeyVal = securityKey.value;
  497. targetWindow.postMessage({ name, data, [securityKey.prop]: securityKey.value }, '*');
  498. }
  499.  
  500. /**
  501. * recieve message posted by postMessage
  502. * @param {string} name - which kind of message you want to recieve
  503. * @param {function} [callback] - if provided, return undefined and call this callback function each time a message
  504. recieved; if not, returns a Promise that will be fulfilled with next message for once
  505. * @returns {(Promise<number>|undefined)}
  506. */
  507. function recieveMessage(name, callback=null) {
  508. const win = typeof unsafeWindow === 'object' ? unsafeWindow : window;
  509. let resolve;
  510. $AEL(win, 'message', function listener(e) {
  511. // Check security key first
  512. if (!(e?.data?.[securityKey.prop] === securityKey.value)) { return; }
  513. if (e?.data?.name === name) {
  514. if (callback) {
  515. callback(e);
  516. } else {
  517. resolve(e);
  518. }
  519. }
  520. });
  521. if (!callback) {
  522. return new Promise((res, rej) => { resolve = res; });
  523. }
  524. }
  525.  
  526. return [postMessage, recieveMessage];
  527. }) ();
  528.  
  529. return { GM_hasVersion, copyPropDescs, randint, randstr, exec, $AEL, postMessage, recieveMessage };
  530. }
  531. }, {
  532. desc: 'compatibility alert',
  533. dependencies: 'utils',
  534. func: () => {
  535. const utils = require('utils');
  536. if (!GM_getValue('compat-alert') && (GM_info.scriptHandler !== 'Tampermonkey' || !utils.GM_hasVersion('5.0'))) {
  537. alert(CONST.Text.CompatAlert);
  538. GM_setValue('compat-alert', true);
  539. }
  540. }
  541. }]);
  542. })();