JSOS API 参考
window.JSOS 系统 API 完整参考
JSOS API 参考
GUI 应用的前端页面(iframe 中的浏览器环境)可以通过 window.JSOS 调用系统功能。注意:这是在浏览器前端调用,而非 Node.js 后端。
推荐: 建议使用 React + coss-ui 组件库开发 GUI 应用,界面风格与系统 UI 更加统一。coss-ui 是与 JSOS 系统组件同源的组件库,提供按钮、对话框、菜单、输入框等基础组件。
使用方式
await window.JSOS.toast({ title: '操作成功', type: 'success' });
const apps = await window.JSOS.getApps();
await window.JSOS.openApp('dev.jsos.terminal');通知
toast(options)
显示系统 Toast 通知。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
title | string | ✓ | 标题 |
description | string | - | 描述 |
type | string | - | default | success | error | info | warning |
timeout | number | - | 显示时长(ms),0 则不自动关闭 |
await window.JSOS.toast({ title: '保存成功', type: 'success' });
await window.JSOS.toast({ title: '出错了', description: '请重试', type: 'error', timeout: 5000 });notify(options)
发送浏览器系统通知。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
title | string | ✓ | 标题 |
body | string | - | 内容 |
icon | string | - | 图标 URL |
await window.JSOS.notify({ title: '下载完成', body: '文件已就绪' });首次调用会请求通知权限。
应用管理
getApps()
获取已安装应用列表。
const apps = await window.JSOS.getApps();
// [{ id, name, icon, version, type, isSystem, isRunning, widgets }]getAppInfo(appId)
获取应用详情。
const info = await window.JSOS.getAppInfo('my-app');
// {
// id, name, description, icon, version, type, isSystem,
// port, isRunning, serverUrl, installedAt,
// defaultWidth, defaultHeight, widgets,
// author, contributors, repository, bugs,
// appDir, dataDir, sourceDirExists, dataDirExists,
// }| 字段 | 类型 | 说明 |
|---|---|---|
appDir | string | null | 应用源码目录绝对路径 |
dataDir | string | null | 应用数据目录绝对路径 |
sourceDirExists | boolean | 源码目录是否存在(应用已启动过则为 true) |
dataDirExists | boolean | 数据目录是否存在 |
openApp(appId, options?)
打开应用。
// 简单打开
await window.JSOS.openApp('terminal-app');
// 带路由(仅 GUI 应用)
await window.JSOS.openApp('dev.jsos.settings', {
route: '/wallpaper',
params: { workspaceId: 'home' }
});route 和 params 会拼接到 iframe URL 的 hash 中:/#/wallpaper?workspaceId=home
openAppWithArgs(appId, options?)
打开应用并传递自定义启动参数。主要用于 CLI 应用,允许自定义启动命令和环境变量。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
appId | string | ✓ | 应用 ID |
options.startCommand | string | - | 自定义启动命令,覆盖 manifest 中的 startCommand |
options.env | object | - | 额外环境变量(不能覆盖 DATA_DIR/APP_DIR/PORT/LANG/JSOS_VERSION/PROXY_URL/PROXY_KEY) |
options.route | string | - | GUI 应用的 hash 路由(如 /window),拼接到 iframe URL 的 # 后 |
options.params | object | - | 路由查询参数,拼接到 route 后的 ? 中 |
// 打开终端并进入指定目录
await window.JSOS.openAppWithArgs('dev.jsos.terminal', {
startCommand: `/bin/jsh -c "cd '/home/user/workspace' && /bin/jsh"`
});
// 打开终端并传递自定义环境变量
await window.JSOS.openAppWithArgs('dev.jsos.terminal', {
startCommand: `/bin/jsh -c "cd /tmp && ls && /bin/jsh"`,
env: { MY_VAR: 'hello' }
});
// GUI 应用:打开设置并直接导航到窗口透明度页面
await window.JSOS.openAppWithArgs('dev.jsos.settings', {
route: '/window'
});注意:
options.env不能覆盖系统变量DATA_DIR、APP_DIR、PORT、LANG、JSOS_VERSION、PROXY_URL、PROXY_KEY。GUI 应用可通过route/params直接导航(等价于openApp的对应参数)。
closeApp(appId)
关闭应用所有窗口。
await window.JSOS.closeApp('my-app');closeAppWindow()
关闭当前调用者的窗口(仅关闭发起调用的 iframe 所在窗口),不影响同应用的其他窗口。
await window.JSOS.closeAppWindow();isAppRunning(appId)
检查应用是否运行。
const { running } = await window.JSOS.isAppRunning('my-app');工作区
getWorkspaces()
const workspaces = await window.JSOS.getWorkspaces();
// [{ id, name, type }]getCurrentWorkspace()
const ws = await window.JSOS.getCurrentWorkspace();switchWorkspace(id)
await window.JSOS.switchWorkspace('ws-123');createWorkspace(name)
const { id } = await window.JSOS.createWorkspace('工作');deleteWorkspace(id)
await window.JSOS.deleteWorkspace('ws-123');renameWorkspace(id, name)
await window.JSOS.renameWorkspace('ws-123', '新名称');壁纸
getWallpaper(workspaceId?)
const wallpaper = await window.JSOS.getWallpaper();
// { type, dataUrl, mimeType, overlay, overlayOpacity, blur }setWallpaper(config)
await window.JSOS.setWallpaper({
type: 'image',
data: 'base64data...',
mimeType: 'image/jpeg',
overlay: 'rgba(0,0,0,0.3)',
overlayOpacity: 30,
blur: 5
});resetWallpaper(workspaceId?)
await window.JSOS.resetWallpaper();语言
getLocale()
const lang = await window.JSOS.getLocale(); // 'zh-CN' / 'en'setLocale(lang)
await window.JSOS.setLocale('en');主题
getTheme()
返回当前有效主题('light' 或 'dark')。
const theme = await window.JSOS.getTheme();setTheme(mode)
await window.JSOS.setTheme('dark'); // 暗色
await window.JSOS.setTheme('light'); // 亮色
await window.JSOS.setTheme('system'); // 跟随系统getThemeMode()
返回用户配置的原始主题模式(含 'system'),用于区分「跟随系统」和显式选择的亮/暗色。
const mode = await window.JSOS.getThemeMode(); // 'light' | 'dark' | 'system'事件监听
onLocaleChange(callback)
监听语言切换。
const unsub = window.JSOS.onLocaleChange((locale) => {
// locale: 'zh-CN' | 'en'
});
// 取消监听
unsub();onThemeChange(callback)
监听主题切换。
window.JSOS.onThemeChange((theme) => {
// theme: 'light' | 'dark'
document.documentElement.classList.toggle('dark', theme === 'dark');
});小组件
addWidget(appId, widgetId, options?)
await window.JSOS.addWidget('my-app', 'todo-list', { x: 300, y: 200 });安装相关
以下 API 主要供应用管理器内部使用。
parseZip(file)
const result = await window.JSOS.parseZip(zipFile);
// { valid, manifest, fileSize, fileCount, installAction, existingVersion, error }installApp(file)
const result = await window.JSOS.installApp(zipFile);uninstallApp(appId, deleteData?)
await window.JSOS.uninstallApp('my-app', true); // 删除数据exportAppSnapshot(appId)
导出应用快照包(包含 WebContainer 运行时快照,安装后可跳过 npm install)。
const result = await window.JSOS.exportAppSnapshot('my-app');
// { success, base64, filename, mimeType }返回的 base64 可直接转换为 Blob 下载:
const bytes = Uint8Array.from(atob(result.base64), c => c.charCodeAt(0));
const blob = new Blob([bytes], { type: result.mimeType || 'application/zip' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = result.filename;
a.click();
URL.revokeObjectURL(url);Dock 设置
getDockSettings()
const { position } = await window.JSOS.getDockSettings();setDockSettings(settings)
await window.JSOS.setDockSettings({ position: 'left' });终端背景
getTerminalBgSettings()
const settings = await window.JSOS.getTerminalBgSettings();
// { opacity, blur }setTerminalBgSettings(settings)
await window.JSOS.setTerminalBgSettings({ opacity: 60, blur: 10 });窗口透明度与磨砂效果
未激活(非聚焦)窗口按该透明度渲染,并叠加磨砂模糊;聚焦窗口始终为 100% 且无模糊。全局生效,持久化在 jsos-workspaces 的 settings store。
getWindowOpacitySettings()
const { inactiveOpacity, inactiveBlur } = await window.JSOS.getWindowOpacitySettings();
// { inactiveOpacity: 90, inactiveBlur: 8 } // 透明度 20–100,模糊 0–30pxsetWindowOpacitySettings(settings)
await window.JSOS.setWindowOpacitySettings({ inactiveOpacity: 60, inactiveBlur: 10 });
await window.JSOS.setWindowOpacitySettings({ inactiveBlur: 12 }); // 只更新模糊| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
inactiveOpacity | number | - | 未激活窗口透明度百分比(20–100),越界值会被 clamp |
inactiveBlur | number | - | 未激活窗口磨砂模糊像素(0–30),越界值会被 clamp;0 表示关闭 |
至少提供其中一个字段;未提供的字段保留当前值。
返回:{ success, error? }
可在 设置 → 窗口 页面调整;聚焦窗口始终 100% 且无模糊,最小化窗口不参与渲染;模糊仅在透明度低于 100% 时可见。
代理设置
代理 API 允许应用配置和使用 CORS 代理服务,用于访问跨域接口。
getProxyConfig()
获取当前代理配置。
const config = await window.JSOS.getProxyConfig();
// { url: 'https://...', key: '...' } 或 nullsetProxyConfig(config)
设置代理配置。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
config.url | string | ✓ | 代理服务地址(Cloudflare Worker 部署地址) |
config.key | string | - | API 认证密钥(可选) |
await window.JSOS.setProxyConfig({
url: 'https://cors-proxy.example.com',
key: 'your-api-key' // 可选
});deleteProxyConfig()
删除代理配置。
await window.JSOS.deleteProxyConfig();proxyFetch(url, options?)
通过代理发起跨域请求。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
url | string | ✓ | 目标 URL(不含代理前缀) |
options | object | - | fetch 选项(method, headers, body 等) |
返回值:{ ok, status, statusText, headers, data }
// GET 请求
const result = await window.JSOS.proxyFetch('https://api.example.com/data');
if (result.ok) {
const data = JSON.parse(result.data);
console.log(data);
}
// POST 请求
const result = await window.JSOS.proxyFetch('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});使用场景:
- 访问跨域 API 接口
- 从外部服务下载文件
- 与其他 Web 服务集成
注意事项:
- 代理配置通过 设置 → 代理 进行管理
- 未配置代理时,此 API 会返回错误
- 响应体以文本形式返回
持久化目录管理
持久化目录(相对 workdir)的内容会被自动监听并快照到 IndexedDB,页面刷新 / 重启后自动恢复。目录列表本身持久化在系统设置中,可通过以下 API 或 jsos persist CLI 增删改,也可以在 设置 → 持久化 页面管理。
路径规则:
- 必须是相对
workdir的路径(如.pi);workdir 绝对路径(如/home/<id>/.pi)会自动转换为相对路径,不能包含..段 - 重复添加同一路径为幂等操作(返回
alreadyExists) - 不能与已有条目互为父子路径(父目录、子目录都会拒绝)
workspace、.tmp为保留前缀
WebContainer 限制: 可持久化的目录必须位于 workdir(
$HOME,即/home/<id>/)内部。workdir 之外的路径(如/home/test)无法被wc.export/wc.mount/wc.fs.watch覆盖,不会生效。
getUserDataDirs()
列出所有持久化目录及其快照状态。
const { dirs } = await window.JSOS.getUserDataDirs();
// [{ path: '.pi', snapshotUpdatedAt: 1763532000000, snapshotSize: 20480 }]| 属性 | 类型 | 说明 |
|---|---|---|
path | string | 目录路径(相对 workdir) |
snapshotUpdatedAt | number | null | 最近一次快照时间(毫秒时间戳),无快照为 null |
snapshotSize | number | null | 快照字节数,无快照为 null |
addUserDataDir(path)
新增持久化目录并立即开始监听。若 IndexedDB 中已有该路径的旧快照则自动恢复(快照内容优先);若目录已有内容且无快照,则立即导出一次初始快照。
const result = await window.JSOS.addUserDataDir('.pi');
// { success: true, restored: false }
const again = await window.JSOS.addUserDataDir('.pi');
// { success: true, restored: false, alreadyExists: true }| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
path | string | ✓ | 目录路径(相对 workdir,如 .pi;也接受 workdir 绝对路径) |
返回值中的 restored 表示是否从旧快照恢复;alreadyExists 为 true 表示该路径已在列表中,本次为幂等成功。
renameUserDataDir(from, to)
重命名持久化目录。优先以容器内当前内容生成新快照,快照键同步改名,数据挂载到新路径,并在数据就位后尽力删除旧路径的实文件。
await window.JSOS.renameUserDataDir('.pi', '.pi-new');| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
from | string | ✓ | 现有目录路径 |
to | string | ✓ | 新目录路径 |
removeUserDataDir(path, options?)
停止持久化指定目录(移出列表并取消监听)。容器内的实际文件不会被删除;默认保留已存快照(再次 addUserDataDir 同路径可恢复)。
await window.JSOS.removeUserDataDir('.pi'); // 保留快照
await window.JSOS.removeUserDataDir('.pi', { purge: true }); // 同时删除快照| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
path | string | ✓ | 目录路径 |
options.purge | boolean | - | true 时同时删除 IndexedDB 中的快照(默认 false) |
返回:{ success, purged }
browseWorkdir(dir?)
浏览 workdir 下的目录(供目录选择器使用,仅返回目录名,不暴露文件内容)。
const root = await window.JSOS.browseWorkdir();
// { dir: '', parent: null, dirs: [{ name: '.pi', reserved: false }, { name: 'workspace', reserved: true }], home: '/home/xxx' }
const sub = await window.JSOS.browseWorkdir('.pi');| 属性 | 类型 | 说明 |
|---|---|---|
dir | string | 当前目录(相对 workdir,根为 '') |
parent | string | null | 上级目录;已在根时为 null |
dirs | Array<{ name, reserved }> | 子目录名列表(含隐藏目录);reserved: true 表示保留目录 |
home | string | workdir 绝对路径(如 /home/<id>) |
内置浏览器
listServers()
列出当前运行中的内部 HTTP 服务(WebContainer 端口 → 访问 URL),供浏览器应用解析 127.0.0.1:PORT。
const { servers } = await window.JSOS.listServers();
// [{ port: 4000, url: 'https://xxx-4000.local-corp.webcontainer-api.io/', appId: 'dev.jsos.settings', name: '设置', icon: '...' }]| 属性 | 类型 | 说明 |
|---|---|---|
port | number | 容器内端口(如 4000) |
url | string | 对应的 WebContainer 访问 URL |
appId | string | null | 关联的应用 ID;终端里手动启动的服务为 null |
name | string | null | 应用名称(已本地化);未注册服务为 null |
icon | string | null | 应用图标;未注册服务为 null |
Daemon 端口(1993)与浏览器自身的服务会被过滤掉。
终端里手动启动的未注册 HTTP 服务(端口 ≥ 3000)被检测到时,JSOS 会弹出 toast 并自动在内置浏览器中打开;同一端口仅自动打开一次,可通过 toast 的「打开」重新打开。
openBrowser(url)
在 JSOS 内置浏览器窗口中打开 URL。
await window.JSOS.openBrowser('https://example.com');
await window.JSOS.openBrowser('127.0.0.1:4000');| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
url | string | ✓ | 外部网址,或 127.0.0.1:PORT 形式的内部服务 |
返回:{ success, windowId?, error? }
说明: 应用页内 target="_blank" 链接与 window.open 会被自动拦截,交给内置浏览器打开(每次调用创建新的浏览器窗口)。如需保留真实标签页行为,可设置 window.__JSOS_NO_LINK_INTERCEPT__ = true。
数据管理
exportAllData()
导出系统所有 IndexedDB 数据为 JSON 对象。可用于创建系统备份。
const data = await window.JSOS.exportAllData();
// { _version: 1, databases: { 'jsos-apps': {...}, 'jsos-widgets': {...}, 'jsos-workspaces': {...} } }导出并下载为文件:
const data = await window.JSOS.exportAllData();
const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `jsos-backup-${new Date().toISOString().slice(0, 10)}.json`;
a.click();
URL.revokeObjectURL(url);importAllData(data)
从 JSON 对象导入数据,清空所有现有数据后恢复。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
data | Object | ✓ | 从 exportAllData() 返回的数据对象 |
注意: 此操作不可逆,会删除所有现有数据。导入成功后需刷新系统使数据生效。
const result = await window.JSOS.importAllData(data);
if (result.success) {
// 导入成功,请刷新系统使数据生效
}系统控制
restart()
重启 JSOS 系统(刷新父窗口页面)。适用于数据导入/清空后需要刷新系统的场景。
await window.JSOS.restart();clearAllData()
清空所有 IndexedDB 数据库,还原系统到初始状态。执行后会自动刷新页面。
注意: 此操作不可逆,会删除所有应用、工作区、壁纸、小组件和用户数据。
const result = await window.JSOS.clearAllData();
if (result.success) {
// 数据已清空,系统将自动刷新
}系统信息
getSystemInfo()
获取系统信息。
const info = await window.JSOS.getSystemInfo();
// { version: '1.0.0' }存储信息
getStorageInfo()
获取浏览器存储信息,包括配额、使用量和持久化状态。
const storage = await window.JSOS.getStorageInfo();
// {
// quota: 1073741824, // 总配额(字节)
// usage: 52428800, // 已使用(字节)
// usageDetails: { // 详细使用情况
// indexedDB: 41943040,
// cache_storage: 10485760,
// },
// persistent: true // 是否为持久化存储
// }| 字段 | 类型 | 说明 |
|---|---|---|
quota | number | 存储总配额(字节) |
usage | number | 已使用存储(字节) |
usageDetails | object | 详细使用情况(按存储类型分类) |
persistent | boolean | 是否为持久化存储(HTTPS 下通常为 true) |
格式化示例:
function formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
const storage = await window.JSOS.getStorageInfo();
console.log(`已使用: ${formatBytes(storage.usage)} / ${formatBytes(storage.quota)}`);
console.log(`使用率: ${((storage.usage / storage.quota) * 100).toFixed(1)}%`);快捷键
getShortcuts()
获取系统快捷键列表。快捷键由核心注册表统一维护,设置页据此展示。
const { shortcuts } = await window.JSOS.getShortcuts();
// [
// { id: 'snapLeft', scope: 'window', keys: 'Ctrl+Shift+←', aliases: [], label: '窗口左半屏', description: '...' },
// ...
// ]| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 快捷键唯一标识 |
scope | 'global' | 'window' | 作用域 |
keys | string | 平台化展示文本(macOS 为 ⌘⇧←,Windows/Linux 为 Ctrl+Shift+←) |
aliases | string[] | 别名列表(如 ⌘P / Ctrl+P),没有别名时为空数组 |
label | string | 当前语言的名称 |
description | string | 当前语言的说明 |
当前快捷键:
| 快捷键 | 作用域 | 说明 |
|---|---|---|
⌘⇧P / Ctrl+Shift+P | global | 命令面板(别名 ⌘P / Ctrl+P) |
⌘⇧← / Ctrl+Shift+← | window | 当前窗口吸附到左半屏 |
⌘⇧→ / Ctrl+Shift+→ | window | 当前窗口吸附到右半屏 |
⌘⇧↑ / Ctrl+Shift+↑ | window | 当前窗口最大化 |
⌘⇧↓ / Ctrl+Shift+↓ | window | 当前窗口还原 |
| ⌘ + ` / Ctrl + ` | window | 切换当前窗口的终端/日志面板 |
终端
前提条件:应用必须在
package.json的jsos字段中声明"terminal": true。
GUI 应用可以通过 Terminal API 创建和管理可读写的终端,无需自行实现终端功能。
配置
{
"jsos": {
"id": "my-app",
"terminal": true,
"startCommand": "node server.js"
}
}terminal.spawn(options?)
创建新终端并执行命令。
| 参数 | 类型 | 默认值 | 说明 |
|---|---|---|---|
command | string | '/bin/jsh' | 要执行的命令 |
args | string[] | [] | 命令参数 |
show | boolean | true | 是否自动显示终端面板 |
// 创建默认 shell 终端
const result = await window.JSOS.terminal.spawn();
console.log('终端 ID:', result.tabId);
// 执行特定命令
await window.JSOS.terminal.spawn({
command: 'node',
args: ['server.js']
});terminal.write(data, tabId?)
向终端写入数据。
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
data | string | ✓ | 要写入的数据 |
tabId | string | - | 终端 ID,不传则写入活跃终端 |
await window.JSOS.terminal.write('ls -la\n');terminal.close(tabId)
关闭终端。
await window.JSOS.terminal.close('term-123456');terminal.list()
获取终端列表。
const terminals = await window.JSOS.terminal.list();
// [{ id: 'term-xxx', title: '终端 1', status: 'running' }]terminal.show(visible?)
显示/隐藏终端面板。
await window.JSOS.terminal.show(); // 显示
await window.JSOS.terminal.show(false); // 隐藏