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

UWP中WebView2调用AddHostObjectToScript无响应并报错的问题

问题解决:WebView2 UWP中AddHostObjectToScript无法传递C#对象

问题重现

使用WebView2的AddHostObjectToScript传递C#对象到UWP应用的WebView中时,触发错误:

The group or resource is not in the correct state to perform the requested operation.

且无法在chrome.webview.hostObjects或chrome.webview.hostObjects.sync中找到目标对象,已尝试保留对象引用、在不同时机添加对象等方法均无效,使用版本为Microsoft.Web.WebView2 1.0.1264.42。

解决方案

1. 修正Com互操作类的定义

将宿主对象类改为显式接口实现,避免ClassInterfaceType.AutoDual在UWP平台的兼容性问题:

[ComVisible(true)]
public interface IExample
{
    string Prop { get; set; }
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class Example : IExample
{
    public string Prop { get; set; } = "example";
}

2. 调整WebView2初始化流程

在UWP中,需确保在导航前添加宿主对象,并显式配置CoreWebView2环境,同时保留对象强引用防止GC回收:

namespace Example_UWP
{
    public sealed partial class MainPage : Page
    {
        // 保留宿主对象的强引用,避免被GC回收
        private Example _exampleHostObject;

        public MainPage()
        {
            InitializeComponent();
            _ = InitializeAsync();
        }

        public async Task InitializeAsync()
        {
            // 显式创建CoreWebView2环境,指定UWP可访问的本地存储路径
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var env = await CoreWebView2Environment.CreateAsync(null, localFolder.Path);
            
            // 确保CoreWebView2完全初始化
            await ExampleView.EnsureCoreWebView2Async(env);

            // 启用脚本支持(默认开启,显式设置更稳妥)
            ExampleView.CoreWebView2.Settings.IsScriptEnabled = true;

            // 初始化宿主对象并添加到脚本环境
            _exampleHostObject = new Example();
            ExampleView.CoreWebView2.AddHostObjectToScript("example", _exampleHostObject);

            // 最后执行导航操作
            ExampleView.Source = new Uri("http://localhost:3000");
            ExampleView.CoreWebView2.OpenDevToolsWindow();
        }
    }
}

3. 前端正确访问宿主对象

在前端代码中,优先使用异步方式获取对象(避免同步访问的时机问题):

// 异步获取并访问
chrome.webview.hostObjects.get('example').then(exampleObj => {
    console.log(exampleObj.Prop); // 输出 "example"
});

// 若确认对象已加载,可使用同步访问
console.log(chrome.webview.hostObjects.sync.example.Prop);

4. 升级WebView2版本

你使用的1.0.1264.42版本存在UWP平台的已知兼容性问题,建议升级到1.0.1587.40及以上的稳定版,可解决部分状态错误问题。


内容的提问来源于stack exchange,提问作者Eduardo Páez Rubio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:45:37