【问题标题】:Why cannot I open links in an external browser in a WebView (UWP)?为什么我无法在 WebView (UWP) 的外部浏览器中打开链接?
【发布时间】:2018-08-04 22:15:30
【问题描述】:

我正在开发一个几乎完成的 Web App 应用程序,该应用程序有一个本地 WebApp 有一些链接,我想在外部浏览器(Edge、Chrome 等)中打开它们。

我的代码分为三部分:

1) Windows 运行时组件:

using System;
using System.Collections.Generic;
using Windows.Foundation.Metadata;
using Windows.Storage;
using Windows.System;

namespace CallJSInterface
{
    [AllowForWeb]
    public sealed class CallJSCSharp
    {
        public async void OpenURL(string url)
        {
            await Launcher.LaunchUriAsync(new Uri(url));
        }
    }
}

2) WebView 代码:

XAML:

<WebView x:Name="webView1" Source="ms-appx-web:///Assets/index.html" NavigationStarting="webView1_NavigationStarting" />

C#:

private void webView1_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
{
    sender.AddWebAllowedObject("CallJSCSharp", pObject: new CallJSCSharp());
}

3) JavaScript (jQuery):

$("a").click(function (event) {
    event.preventDefault();
    CallJSCSharp.OpenURL($(this).attr('href'));
});

但是什么也没有发生,没有错误,没有消息,什么都没有。有谁知道我应该改变什么?感谢您的帮助。

附加信息:

我对两个项目使用相同的配置。

【问题讨论】:

    标签: c# webview hyperlink uwp windows-10-universal


    【解决方案1】:

    有两个问题导致代码无法工作。

    首先 - Windows 运行时组件自动修改命名约定以匹配执行它的目标平台。因为 JavaScript 方法名按惯例以小写字母开头,所以您必须像这样调用 OpenURL 方法:

    CallJSCSharp.openURL($(this).attr('href'));
    

    现在您应该能够在 Windows 运行时组件中设置断点并查看实际调用的方法。但是还有另一个问题——OpenURL 方法没有在 UI 线程上调用,这是Launcher 正常工作所必需的。要避免这种情况,您需要使用Dispatcher:

    [AllowForWeb]
    public sealed class CallJSCSharp
    {
        public async void OpenURL(string url)
        {
            await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                async () => { 
                     await Launcher.LaunchUriAsync(new Uri(url)); 
                });
        }
    }
    

    进行此更改后,代码应该可以按预期工作。

    最后 - 感谢您提出完美的问题 :-)。

    【讨论】:

    • 很高兴听到这个消息:-),编码愉快!
    • awaitRunAsync 调用没有什么意义。如果由于某种原因调用抛出(例如,URI 格式错误),这也会使应用程序崩溃。
    猜你喜欢
    • 2014-07-12
    • 2018-02-11
    • 2017-08-06
    • 1970-01-01
    • 2015-12-09
    • 2012-09-24
    • 2019-11-23
    • 2021-05-21
    • 2021-06-12
    相关资源
    最近更新 更多