Open links in external browser in WebView (WinRT)

孤街醉人 提交于 2019-12-06 19:50:17

问题


I have a WebView component that I use to display HTML Ads in my app. When user clicks an Ad in the WebView I want to open the Ad link in an external browser. How do I do that?

I need something like OnNavigating from the WP7 browser. I tried the Tapped event of the WebView but it never gets called even when I set IsTapEnabled=true. I need something like


回答1:


You will need to use the ScriptNotify event for this. Here's how I handled the scenario (using NavigateToString). If you're retrieving the web view content from a URL, you will need be able to modify the HTML for this to work.

  1. Add the following Javascript code to your HTML

    <script type="text/javascript">for (var i = 0; i < document.links.length; i++) { document.links[i].onclick = function() { window.external.notify('LaunchLink:' + this.href); return false; } }</script>
    

    This adds an onclick handler to every link (<a href="..."></a>) on the page. window.external.notify is a Javascript method that works in the Webview.

  2. Add the ScriptNotify event handler to the webview.

    WebView.ScriptNotify += WebView_ScriptNotify;
    
  3. Declare the event handler

    async private void WebView_ScriptNotify(object sender, NotifyEventArgs e)
    {
        try
        {
            string data = e.Value;
            if (data.ToLower().StartsWith("launchlink:"))
            {
                await Launcher.LaunchUriAsync(new Uri(data.Substring("launchlink:".Length), UriKind.Absolute));
            }
        }
        catch (Exception)
        {
            // Could not build a proper Uri. Abandon.
        }
    }
    

Note that you if you're using an external URL, this has to be added to the webview's allowed Uris whitelist (http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.scriptnotify for reference).




回答2:


Try to handle NavigationStarting event. Here you can intercept and cancel loading of URL. You can filter which link to open in web view, and which to open in the default browser.

private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        if(null != args.Uri && args.Uri.OriginalString == "URL OF INTEREST")
        {
            args.Cancel = true;
            await Launcher.LaunchUriAsync(args.Uri);
        }
    }


来源:https://stackoverflow.com/questions/12703698/open-links-in-external-browser-in-webview-winrt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!