You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tauri应用构建完成后动态添加资源并提供访问

Tauri 动态添加资源并离线访问方案

一、手动添加Zip资源(初期方案)

1. 定位应用Resources目录

安装后不同系统的Resources路径:

  • Windows:C:\Program Files\[你的应用名称]\resources
  • macOS:/Applications/[你的应用名称].app/Contents/Resources
  • Linux:/opt/[你的应用名称]/resources

2. 部署Zip内容

将包含HTML的Zip包手动解压到Resources下的子目录(比如resources/offline-demos/demo1),确保解压后存在可作为入口的HTML文件(如index.html)。

3. 配置Tauri安全规则

修改tauri.conf.json,允许应用访问本地文件系统资源:

{
  "tauri": {
    "security": {
      "assetProtocol": {
        "scope": ["**"]
      },
      "csp": "default-src 'self' data: filesystem:;"
    }
  }
}

filesystem: 授权访问本地文件,assetProtocol.scope 放开资源访问范围。

4. 前端通过Iframe加载资源

借助Tauri的路径API获取Resources目录,拼接HTML路径后传给iframe:

import { appDir, join } from '@tauri-apps/api/path';

async function loadManualContent() {
  const resourcesDir = await appDir();
  const htmlFilePath = await join(resourcesDir, 'offline-demos', 'demo1', 'index.html');
  // 转换为file协议路径供iframe加载
  document.getElementById('content-frame').src = `file://${htmlFilePath}`;
}

注意:macOS/Linux下需确保应用对Resources目录有读取权限。

二、运行时下载离线存储(最终方案)

1. 选择合适的存储目录

避免写入需要管理员权限的安装目录,改用Tauri提供的应用专属数据目录(appDataDir()),该目录无需特殊权限,适合存储用户下载内容。

2. 实现下载与解压逻辑

步骤1:添加Zip处理插件

在Cargo.toml中引入tauri-plugin-zip:

[dependencies]
tauri-plugin-zip = "2.0"

在tauri.conf.json注册插件:

{
  "tauri": {
    "plugins": {
      "zip": {}
    }
  }
}

步骤2:下载并解压Zip包

import { download } from '@tauri-apps/api/http';
import { appDataDir, join } from '@tauri-apps/api/path';
import { createDir } from '@tauri-apps/api/fs';

async function downloadOfflineContent(contentId, downloadUrl) {
  const dataDir = await appDataDir();
  const downloadsDir = await join(dataDir, 'downloads');
  const extractDir = await join(dataDir, 'offline-content', contentId);

  // 确保目录存在
  await createDir(downloadsDir, { recursive: true });
  await createDir(extractDir, { recursive: true });

  // 下载Zip包到临时目录
  const zipSavePath = await join(downloadsDir, `${contentId}.zip`);
  await download(downloadUrl, zipSavePath);

  // 解压到内容目录
  await window.__TAURI__.zip.extract(zipSavePath, extractDir);
}

3. 管理离线内容

  • 用localStorage或SQLite维护已下载内容的元数据(ID、存储路径、标题等),方便展示离线列表。
  • 提供删除功能,删除对应目录及元数据记录,避免磁盘空间浪费。

4. 加载离线内容到Iframe

async function loadDownloadedContent(contentId) {
  const dataDir = await appDataDir();
  const htmlFilePath = await join(dataDir, 'offline-content', contentId, 'index.html');
  document.getElementById('content-frame').src = `file://${htmlFilePath}`;
}

内容的提问来源于stack exchange,提问作者Ross Lote

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 20:44:54