gpt4 book ai didi

c# - 在 iOS 上引发的 Xamarin.Forms.WebView.Navigating 事件用于内部导航

转载 作者:可可西里 更新时间:2023-11-01 05:19:48 25 4
gpt4 key购买 nike

假设您想要阻止用户从您的 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 加载源代码时也会引发 Navigating 事件,其 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 事件是从内部导航引发的还是因为用户单击了链接。

如何解决这个问题?

最佳答案

我不确定是否可以在开箱即用的 Xamarin Forms 中进行检测,但可以使用自定义渲染器轻松确定导航类型。在您的自定义 iOS 渲染器中,分配一个 WebViewDelegate 并在该委托(delegate)类中覆盖 ShouldStartLoad(),如下所示:

public class CustomWebViewRenderer : WebViewRenderer {

#region Properties

public CustomWebView CustomWebViewItem { get { return Element as CustomWebView; } }

#endregion

protected override void OnElementChanged(VisualElementChangedEventArgs e) {
base.OnElementChanged(e);

if(e.OldElement == null) {
Delegate = new CustomWebViewDelegate(); //Assigning the delegate
}
}
}
internal class CustomWebViewDelegate : UIWebViewDelegate {

public override bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {

if(navigationType == UIWebViewNavigationType.LinkClicked) {
//To prevent navigation when a link is click, return false
return false;
}

return true;
}
}

您还可以显示一个 bool 属性甚至一个枚举备份到您的 Xamarin Forms WebView,它会说明 Navigating 事件是来自被点击的链接还是来自其他东西,尽管也需要自定义渲染器。

关于c# - 在 iOS 上引发的 Xamarin.Forms.WebView.Navigating 事件用于内部导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37298586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com