问题描述
我有一个WebView组件,可用于在我的应用中显示HTML广告.当用户单击WebView中的广告时,我想在外部浏览器中打开广告"链接.我该怎么办?
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?
我需要类似WP7浏览器中的OnNavigating之类的东西.我尝试了WebView的Tapped事件,但是即使设置了IsTapEnabled = true,它也从未被调用.我需要
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
推荐答案
您将需要使用ScriptNotify事件.这是我处理场景的方法(使用NavigateToString).如果要从URL检索Web视图内容,则需要能够修改HTML才能使其正常工作.
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.
-
将以下Javascript代码添加到HTML
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>
这会将onclick处理程序添加到页面上的每个链接(< a href ="..."></a>). window.external.notify是可在Webview中使用的Javascript方法.
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.
将ScriptNotify事件处理程序添加到Webview.
Add the ScriptNotify event handler to the webview.
WebView.ScriptNotify += WebView_ScriptNotify;
声明事件处理程序
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.
}
}
请注意,如果您使用的是外部URL,则必须将其添加到网络视图的允许的Uris白名单(供参考).
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).
这篇关于在WebView(WinRT)的外部浏览器中打开链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!