我有一个自定义hybridWebView for android和ios加载URL。我需要的是在URL完成加载后将回调传递给内容页面。代码如下,帮助将非常感激。
内容页
public partial class ConveyancingLeadPage : ContentPage
{
DashboardViewModel viewmodel;
StorageService storage = new StorageService();
public ConveyancingLeadPage()
{
InitializeComponent();
GetUserAvatar();
}
protected async override void OnAppearing()
{
// I need the callback to be execute here
customView.weblink = viewmodel.BrokerData.config.conveyancing.listing_webview;
}
}
Android HybridView
[assembly: ExportRenderer(typeof(HCHybridWebview), typeof(HCHybridWebviewRendererAndroid))]
namespace HashChing.Droid.CustomRenderers
{
public class HCHybridWebviewRendererAndroid : ViewRenderer<HCHybridWebview, Android.Webkit.WebView>
{
Context _context;
public HCHybridWebviewRendererAndroid(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<HCHybridWebview> e)
{
base.OnElementChanged(e);
const string JavascriptFunction = "function invokeCSharpAction(data){jsBridge.invokeAction(data);}";
if (Control == null)
{
//Do something
if (e.NewElement != null)
{
//Load URL
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
var hybridWebView = e.NewElement as HCHybridWebview;
if (hybridWebView != null)
{
hybridWebView.RefreshView += LoadUrl;
}
}
加载网址
public void LoadUrl(object sender, EventArgs e)
{
Control.LoadUrl(webView.weblink, headers);
}
一旦加载了URL,它将在同一个类中导航到此方法,这是我想在“OnPageFinished”方法内完成加载后将回调传递给我的内容页面的地方。帮助会非常感激。
public class JavascriptWebViewClient : WebViewClient
{
string _javascript;
public JavascriptWebViewClient(string javascript)
{
_javascript = javascript;
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
您可以使用MessagingCenter发送和获取回调:
在您的ContentPage中,例如Page1.xaml.cs
public Page1 ()
{
InitializeComponent ();
//here you could get the callback,and arg = "this is call back"
MessagingCenter.Subscribe<Page1,string>(this,"callback", (send, arg) =>
{
Console.WriteLine(arg);
});
}
然后在你的OnPageFinished
方法:
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
//send the callback content,Parameters can be defined by yourself
MessagingCenter.Send<Page1,string>(new Page1(), "callback","this is call back");
}
更多信息:MessagingCenter
在自定义程序中创建自己的事件LoadCompleted,并在加载完成后从自定义类中调用它。
在您的JavascriptWebViewClient类中,您可以订阅该事件并执行您当时想做的任何事情。
万一你需要它:Events in c#
public partial class ConveyancingLeadPage : ContentPage
{
protected async override void OnAppearing()
{
customView.weblink = viewmodel.BrokerData.config.conveyancing.listing_webview;
// I need the callback to be execute here
customView.LoadCompleted+=LoadCompleted;
}
}