msgbox

建立於 10 小時前
更新於 10 小時前
一个轻量级、无依赖的 JavaScript 对话框库,支持警告框、确认框和输入框,自动适配亮色/深色主题。
總安裝量
3
今日新增
+3
使用者評分
- / 5.0 (0)
目前版本
1.0.0
// @require https://scriptcat.org/lib/4824/1.0.0/msgbox.js?sha384-2b+HiepDy7b/ukGsHoWqQ9f3y9aWpLdynlZXUp6a8m9wQYCSqUlTepC2YCoHfjOG
庫詳情
這是一個使用者腳本使用的庫,你可以在你的腳本中直接引用它。

MsgBox 使用说明文档

一个轻量级、无依赖的 JavaScript 对话框库,支持警告框、确认框和输入框,自动适配亮色/深色主题。


📦 快速开始

安装

将以下代码添加到您的 HTML 文件中:

<script src="path/to/msgbox.js"></script>

基础用法

// 警告框
await window.msgbox.showAlert('操作成功!');

// 确认框
const confirmed = await window.msgbox.showConfirm('确定要删除吗?');
if (confirmed) {
    console.log('用户确认删除');
}

// 输入框
const input = await window.msgbox.showPrompt('请输入您的名字:');
if (input !== false) {
    console.log('用户输入:', input);
}

📖 API 文档

1. showAlert - 警告对话框

显示一个警告对话框,用户只能点击确定按钮。

语法

await window.msgbox.showAlert(message, options)

参数

参数 类型 必填 默认值 说明
message string - 对话框显示的消息内容
options object {} 配置选项
options.title string '提示' 对话框标题
options.okText string '确定' 确认按钮文字
options.theme string 'auto' 主题模式:'light'​、'dark'​、'auto'

返回值

  • 类型​: Promise<void>
  • 说明: Promise 在用户点击确定按钮后 resolve

示例

// 基础用法
await window.msgbox.showAlert('操作成功!');

// 自定义标题和按钮
await window.msgbox.showAlert('文件已保存到本地', {
    title: '保存成功',
    okText: '知道了'
});

// 使用深色主题
await window.msgbox.showAlert('这是深色主题提示', {
    title: '提示',
    theme: 'dark'
});

// 在函数中使用
async function saveData() {
    try {
        await api.save();
        await window.msgbox.showAlert('保存成功!', {
            title: '成功',
            okText: '好的'
        });
    } catch (error) {
        await window.msgbox.showAlert('保存失败:' + error.message, {
            title: '错误'
        });
    }
}

2. showConfirm - 确认对话框

显示一个确认对话框,用户可以选择确定或取消。

语法

const result = await window.msgbox.showConfirm(message, options)

参数

参数 类型 必填 默认值 说明
message string - 对话框显示的消息内容
options object {} 配置选项
options.title string '确认' 对话框标题
options.okText string '确定' 确认按钮文字
options.cancelText string '取消' 取消按钮文字
options.theme string 'auto' 主题模式:'light'​、'dark'​、'auto'

返回值

  • 类型​: Promise<boolean>

  • 说明:

    • true - 用户点击了确定按钮
    • false - 用户点击了取消按钮、按下 ESC 键或点击遮罩层

示例

// 基础用法
const confirmed = await window.msgbox.showConfirm('确定要删除这条记录吗?');
if (confirmed === true) {
    // 执行删除操作
    await deleteRecord();
} else {
    console.log('用户取消了删除');
}

// 自定义所有文字
const result = await window.msgbox.showConfirm(
    '此操作不可恢复,确定要继续吗?',
    {
        title: '危险操作',
        okText: '确认删除',
        cancelText: '我再想想'
    }
);

// 退出登录确认
async function handleLogout() {
    const confirmed = await window.msgbox.showConfirm('确定要退出登录吗?', {
        title: '退出确认',
        okText: '确定',
        cancelText: '取消'
    });
    
    if (confirmed) {
        await logout();
        window.location.href = '/login';
    }
}

// 表单提交前确认
async function submitForm(data) {
    const confirmed = await window.msgbox.showConfirm(
        '确定要提交表单吗?提交后将无法修改。',
        {
            title: '提交确认',
            okText: '提交',
            cancelText: '取消'
        }
    );
    
    if (confirmed) {
        await api.submit(data);
        await window.msgbox.showAlert('提交成功!');
    }
}

3. showPrompt - 输入对话框

显示一个输入对话框,用户可以输入文本内容。

语法

const result = await window.msgbox.showPrompt(message, defaultValue, options)

参数

参数 类型 必填 默认值 说明
message string - 对话框显示的消息内容
defaultValue string '' 输入框的默认值
options object {} 配置选项
options.title string '输入' 对话框标题
options.okText string '确定' 确认按钮文字
options.cancelText string '取消' 取消按钮文字
options.placeholder string '' 输入框占位符
options.theme string 'auto' 主题模式:'light'​、'dark'​、'auto'

返回值

  • 类型​: Promise<string | false>

  • 说明:

    • string​ - 用户输入的内容(可以是空字符串 ''
    • false - 用户点击了取消按钮、按下 ESC 键或点击遮罩层

特殊行为

  • ✅ 打开对话框时,输入框自动获得焦点并选中默认文本
  • ✅ 按 Enter 键提交输入
  • ✅ 按 ESC​ 键取消输入(返回 false
  • ✅ 允许输入空字符串

示例

// 基础用法
const name = await window.msgbox.showPrompt('请输入您的名字:');
if (name !== false) {
    console.log('用户输入了:', name);
    if (name === '') {
        console.log('输入为空字符串');
    }
} else {
    console.log('用户取消了输入');
}

// 带默认值
const username = await window.msgbox.showPrompt('请输入用户名:', 'admin');
if (username !== false) {
    console.log('用户名:', username);
}

// 完整配置
const email = await window.msgbox.showPrompt(
    '请输入您的邮箱地址:',
    'user@example.com',
    {
        title: '邮箱设置',
        okText: '保存',
        cancelText: '取消',
        placeholder: 'example@email.com',
        theme: 'auto'
    }
);

if (email !== false) {
    if (email === '') {
        await window.msgbox.showAlert('邮箱不能为空', {
            title: '验证失败'
        });
    } else if (!isValidEmail(email)) {
        await window.msgbox.showAlert('邮箱格式不正确', {
            title: '验证失败'
        });
    } else {
        await api.saveEmail(email);
        await window.msgbox.showAlert('邮箱保存成功!');
    }
}

// 重命名文件
async function renameFile(currentName) {
    const newName = await window.msgbox.showPrompt(
        '请输入新的文件名:',
        currentName,
        {
            title: '重命名文件',
            okText: '重命名',
            cancelText: '取消'
        }
    );
    
    if (newName === false) {
        return; // 用户取消
    }
    
    if (newName === '') {
        await window.msgbox.showAlert('文件名不能为空', {
            title: '错误'
        });
        return;
    }
    
    if (newName === currentName) {
        await window.msgbox.showAlert('文件名未改变');
        return;
    }
    
    try {
        await api.rename(currentName, newName);
        await window.msgbox.showAlert('重命名成功!');
    } catch (error) {
        await window.msgbox.showAlert('重命名失败:' + error.message, {
            title: '错误'
        });
    }
}

// 添加备注(允许空值)
async function addNote(itemId) {
    const note = await window.msgbox.showPrompt(
        '请输入备注信息(可选):',
        '',
        {
            title: '添加备注',
            placeholder: '在这里输入备注...',
            okText: '保存',
            cancelText: '取消'
        }
    );
    
    if (note !== false) {
        // note 可以是空字符串,这是合法的
        await api.saveNote(itemId, note);
        await window.msgbox.showAlert(
            note === '' ? '备注已清空' : '备注已保存'
        );
    }
}

// 搜索功能
async function showSearchDialog() {
    const keyword = await window.msgbox.showPrompt(
        '请输入搜索关键词:',
        '',
        {
            title: '搜索',
            placeholder: '输入关键词...',
            okText: '搜索',
            cancelText: '取消'
        }
    );
    
    if (keyword !== false && keyword !== '') {
        await performSearch(keyword);
    }
}

🎨 主题模式

三种主题模式

模式 说明 使用场景
'auto' 自动检测系统主题(默认) 推荐使用,自适应用户系统设置
'light' 强制使用亮色主题 适合浅色背景的页面
'dark' 强制使用深色主题 适合深色背景的页面或夜间模式

主题颜色方案

亮色主题 (Light Mode)

{
    bg: '#ffffff',           // 背景色:白色
    title: '#333333',        // 标题颜色:深灰
    text: '#666666',         // 文本颜色:中灰
    primaryBtn: '#007bff',   // 主按钮:蓝色
    cancelBtn: '#e9ecef',    // 取消按钮:浅灰
    cancelBtnText: '#333333' // 取消按钮文字:深灰
}

深色主题 (Dark Mode)

{
    bg: '#2d2d2d',           // 背景色:深灰
    title: '#ffffff',        // 标题颜色:白色
    text: '#e0e0e0',         // 文本颜色:浅灰
    primaryBtn: '#0d6efd',   // 主按钮:亮蓝
    cancelBtn: '#4a4a4a',    // 取消按钮:灰色
    cancelBtnText: '#ffffff' // 取消按钮文字:白色
}

主题使用示例

// 自动检测系统主题(推荐)
await window.msgbox.showAlert('自动适配主题', {
    theme: 'auto' // 默认值,可省略
});

// 强制亮色主题
await window.msgbox.showAlert('亮色主题提示', {
    theme: 'light'
});

// 强制深色主题(适合警告或危险操作)
await window.msgbox.showConfirm('确定要删除所有数据吗?', {
    title: '危险操作',
    theme: 'dark'
});

💡 使用技巧

1. 简化代码 - 解构赋值

// 在文件顶部解构
const { showAlert, showConfirm, showPrompt } = window.msgbox;

// 然后可以直接使用
await showAlert('操作成功!');
const confirmed = await showConfirm('确定删除吗?');
const input = await showPrompt('请输入:');

2. 封装常用对话框

// 封装成功提示
async function showSuccess(message) {
    return await window.msgbox.showAlert(message, {
        title: '✓ 成功',
        okText: '好的'
    });
}

// 封装错误提示
async function showError(message) {
    return await window.msgbox.showAlert(message, {
        title: '✗ 错误',
        okText: '知道了',
        theme: 'dark'
    });
}

// 封装警告提示
async function showWarning(message) {
    return await window.msgbox.showAlert(message, {
        title: '⚠ 警告',
        okText: '明白了'
    });
}

// 封装删除确认
async function confirmDelete(itemName) {
    return await window.msgbox.showConfirm(
        `确定要删除"${itemName}"吗?此操作不可撤销!`,
        {
            title: '删除确认',
            okText: '确认删除',
            cancelText: '取消',
            theme: 'dark'
        }
    );
}

// 封装输入验证
async function promptWithValidation(message, validator, options = {}) {
    while (true) {
        const input = await window.msgbox.showPrompt(message, '', options);
        
        if (input === false) {
            return false; // 用户取消
        }
        
        const error = validator(input);
        if (!error) {
            return input; // 验证通过
        }
        
        // 验证失败,显示错误并重新输入
        await showError(error);
    }
}

// 使用示例
await showSuccess('保存成功!');
await showError('网络连接失败');
await showWarning('该功能即将下线');

if (await confirmDelete('重要文件.txt')) {
    // 执行删除
}

const email = await promptWithValidation(
    '请输入邮箱:',
    (value) => {
        if (!value) return '邮箱不能为空';
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) return '邮箱格式不正确';
        return null; // 验证通过
    },
    { title: '邮箱验证', placeholder: 'your@email.com' }
);

3. 与前端框架集成

Vue 3 集成

// composables/useMsgBox.js
export function useMsgBox() {
    return {
        showAlert: window.msgbox.showAlert,
        showConfirm: window.msgbox.showConfirm,
        showPrompt: window.msgbox.showPrompt
    };
}

// 在组件中使用
import { useMsgBox } from '@/composables/useMsgBox';

export default {
    setup() {
        const { showAlert, showConfirm, showPrompt } = useMsgBox();
        
        const handleDelete = async () => {
            const confirmed = await showConfirm('确定删除吗?');
            if (confirmed) {
                // 执行删除
                await showAlert('删除成功!');
            }
        };
        
        return { handleDelete };
    }
};

React 集成

// hooks/useMsgBox.js
export const useMsgBox = () => {
    return {
        showAlert: window.msgbox.showAlert,
        showConfirm: window.msgbox.showConfirm,
        showPrompt: window.msgbox.showPrompt
    };
};

// 在组件中使用
import { useMsgBox } from './hooks/useMsgBox';

function MyComponent() {
    const { showAlert, showConfirm, showPrompt } = useMsgBox();
    
    const handleDelete = async () => {
        const confirmed = await showConfirm('确定删除吗?');
        if (confirmed) {
            // 执行删除
            await showAlert('删除成功!');
        }
    };
    
    return <button onClick={handleDelete}>删除</button>;
}