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

如何在UWP应用的WebView中通过JS获取应用本地文件夹路径?

如何在UWP WebView的JS中获取应用本地文件夹路径

WebView中的JavaScript处于沙箱环境,无法直接访问UWP应用的系统路径,必须通过UWP原生代码与JS的双向通信实现路径传递,以下是具体方案:

核心步骤

1. 在UWP原生代码中获取应用本地路径

UWP提供系统API可直接获取应用沙箱内的本地文件夹路径,对应你提到的C:/Users/[USER_NAME]/AppData/Local/Packages/[MY_APP_NAME]/LocalState(默认本地数据目录):

// C# 代码示例
string localFolderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path;

2. 建立原生代码与JS的通信

有两种常用方式实现路径传递:

方式一:原生主动向JS注入路径

在WebView加载完成后,调用InvokeScriptAsync执行指定JS函数,将路径传入:

// UWP端代码
await webView.InvokeScriptAsync("setLocalFolderPath", new string[] { localFolderPath });

对应的JS代码:

// Web端JS代码
function setLocalFolderPath(path) {
    // 在此处使用或存储路径
    console.log("应用本地文件夹路径:", path);
}

方式二:JS主动请求路径

通过ScriptNotify事件实现JS向原生发起请求,原生返回路径:

  • UWP端代码:
// 注册ScriptNotify事件
webView.ScriptNotify += WebView_ScriptNotify;

private void WebView_ScriptNotify(object sender, NotifyEventArgs e)
{
    if (e.Value == "requestLocalPath")
    {
        string path = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
        // 将路径返回给JS
        webView.InvokeScriptAsync("receiveLocalPath", new string[] { path });
    }
}
  • Web端JS代码:
// 向原生发起路径请求
window.external.notify("requestLocalPath");

// 接收原生返回的路径
function receiveLocalPath(path) {
    console.log("获取到的应用本地路径:", path);
}

注意事项

  • 若WebView加载的是外部网页,需在Package.appxmanifest中配置AllowScriptNotifyForWebPages权限;加载本地网页则默认允许。
  • UWP应用仅能访问自身沙箱内的目录,上述方法获取的是应用合法的本地数据目录,符合系统安全机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:25:25