【发布时间】:2016-09-14 21:06:36
【问题描述】:
假设您想阻止用户从您的 Xamarin.Forms.WebView 导航到外部页面。
public App ()
{
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = "<h1>Hello world</h1><a href='http://example.com'>Can't escape!</a><iframe width='420' height='315' src='https://www.youtube.com/embed/oHg5SJYRHA0' frameborder='0' allowfullscreen></iframe>"
}
};
webView.Navigating += WebView_Navigating;
MainPage = new ContentPage {
Content = webView
};
}
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
// we don't want to navigate away from our page
// open it in a new page instead etc.
e.Cancel = true;
}
这在 Windows 和 Android 上运行良好。但在 iOS 上,它根本不加载!
在 iOS 上,即使从 HtmlWebViewSource 加载源代码也会引发导航事件,其 URL 类似于 file:///Users/[user]/Library/Developer/CoreSimulator/Devices/[deviceID]/data/Containers/Bundle/Application/[appID]/[appName].app/
好的,所以你可以通过以下方式解决这个问题:
private void WebView_Navigating(object sender, WebNavigatingEventArgs e)
{
if (e.Url.StartsWith("file:") == false)
e.Cancel = true;
}
页面最终在 iOS 上加载。耶。可是等等!嵌入的 YouTube 视频无法加载!这是因为 Navigating 事件会针对 iframe 甚至外部脚本(如 Twitter 的 <script charset="utf-8" type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>)等嵌入式资源的内部导航引发,但仅限于 iOS!
我找不到方法来确定 Navigating 事件是由内部导航引发还是因为用户单击了链接。
如何解决这个问题?
【问题讨论】:
标签: c# ios webview xamarin xamarin.forms