如何在 WebView2 上启用扩展

Posted

技术标签:

【中文标题】如何在 WebView2 上启用扩展【英文标题】:How to enable extension on WebView2 【发布时间】:2020-07-30 10:27:21 【问题描述】:

我在 Microsoft Edge (Chromium) 上安装了 Chrome 扩展程序来播放 HLS 视频。我已经尝试过 Microsoft Edge (Chromium),它运行良好。 HLS URL 为 http://localhost/hls/taiguo/playlist.m3u8,在 Microsoft Edge 浏览器上显示 URL 如下:extension://ekcifneimckhkjdfklkkpdlnckcjhmke/index.html#http://localhost/hls/taiguo/playlist.m3u8。

当我按照 [WebView2 入门(开发者预览)] (https://docs.microsoft.com/en-us/microsoft-edge/hosting/webview2/gettingstarted) 示例代码使用 WebView2 将浏览器嵌入到 Windows 应用程序中时:

` CreateCoreWebView2EnvironmentWithDetails(nullptr, nullptr, nullptr, 打回来( [hWnd](HRESULT 结果,ICoreWebView2Environment* env) -> HRESULT

    RETURN_IF_FAILED(result);
    // Create a CoreWebView2Host and get the associated CoreWebView2 whose parent is the main window hWnd
    env->CreateCoreWebView2Host(hWnd, Callback<ICoreWebView2CreateCoreWebView2HostCompletedHandler>(
        [hWnd](HRESULT result, ICoreWebView2Host* host) -> HRESULT 
        if (host != nullptr) 
            webviewHost = host;
            webviewHost->get_CoreWebView2(&webviewWindow);
        

        // Add a few settings for the webview
        // this is a redundant demo step as they are the default settings values
        ICoreWebView2Settings* Settings;
        webviewWindow->get_Settings(&Settings);
        Settings->put_IsScriptEnabled(TRUE);
        Settings->put_AreDefaultScriptDialogsEnabled(TRUE);
        Settings->put_IsWebMessageEnabled(TRUE);

        // Resize WebView to fit the bounds of the parent window
        RECT bounds;
        GetClientRect(hWnd, &bounds);
        webviewHost->put_Bounds(bounds);

        // Schedule an async task to navigate to Bing
        webviewWindow->Navigate(L"http://localhost/hls/taiguo/playlist.m3u8");`

如果我运行上面的代码,应用程序只会下载 playlist.m3u8 文件而不播放视频。如果我将 webviewWindow->Navigate(...) 的 URL 参数更改为:

webviewWindow->Navigate(L"extension://ekcifneimckhkjdfklkkpdlnckcjhmke/index.html#http://localhost/hls/taiguo/playlist.m3u8");

然后我收到如下所示的错误消息: App screen capture

我希望有人能告诉我如何使用 WebView2 API 运行扩展。

【问题讨论】:

【参考方案1】:

我从事 WebView2 项目。让我首先说 WebView2 目前不支持扩展。这是一个相当复杂的功能,我们必须做出很多设计选择,所以在解决这些问题之前,我们会故意关闭扩展。我们绝对愿意在未来支持它,我们的反馈回购跟踪功能请求存在问题 - https://github.com/MicrosoftEdge/WebViewFeedback/issues/81。很高兴让您插话并谈论您的用例,因此我们对您正在寻找的内容有更多的背景信息。例如,开发人员为他们的应用程序启用任意扩展(例如,我希望有一个广告拦截器来监视我的网络内容),我认为这就是您所要求的,这与为最终用户提供一种安装扩展程序的方法非常不同网页浏览。

也就是说,从技术角度来看,即使 WebView2 现在支持扩展,用户从浏览器安装的扩展也不会显示在 WebView2 中。浏览器将其扩展存储在其用户数据文件夹中(请参阅 C:\Users\username\AppData\Local\Microsoft\Edge SxS\User Data\Default\Extensions for Canary),其中还包含类似cookie、缓存等。WebView2 应用有自己的用户数据文件夹,由于安全隐患,不能使用浏览器用户数据。

【讨论】:

那么,有没有办法手动添加扩展?我有自己的扩展作为清单和 js 文件。有没有办法将它们加载到 WebView2?

以上是关于如何在 WebView2 上启用扩展的主要内容,如果未能解决你的问题,请参考以下文章

WebView2:如何启用密码自动填充?

WebView2如何加载本地文件?

如何在Visual Studio工具栏中添加WebView2控件?

如何在 xampp linux 上启用 mcrypt php 扩展

如何检测在 iOS 8 上包含应用程序时启用了应用程序扩展?

如何在 Webview2 中使用透明度?