本文介绍了Xamarin.Forms ShouldOverrideUrlLoading 触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 JavascriptWebViewClient.cs 中使用 ShouldOverrideUrlLoading 触发 mainpage.xaml 中的活动指示器.

I want to trigger the activityindicator in mainpage.xaml using ShouldOverrideUrlLoading inside JavascriptWebViewClient.cs.

MyJavascriptWebViewClient.cs:

MyJavascriptWebViewClient.cs:

 public class JavascriptWebViewClient : WebViewClient
{

    readonly string _javascript;

    public JavascriptWebViewClient(string javascript)
    {
        _javascript = javascript;


    }


    [Obsolete]
    public override bool ShouldOverrideUrlLoading(WebView view, string url)
    {
        view.LoadUrl(url);


        Toast.MakeText(Android.App.Application.Context, "Loading...", ToastLength.Long).Show();

        Console.WriteLine("Page Changing Now..");

        return true;
    }

    public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
    {
       // DependencyService.Get<ILoadingIndicator>().Show();

        base.OnPageStarted(view, url, favicon);
        Console.WriteLine("Sayfa Doluyor.");
    }

    public override void OnPageFinished(WebView view, string url)
    {
        base.OnPageFinished(view, url);
        view.EvaluateJavascript(_javascript, null);
        Console.WriteLine("Sayfa Doldu");
    }



}

Mainpage.xaml 代码:

Mainpage.xaml code:

<ContentPage
x:Class="XFHybridWebViewAdvDemo.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:XFHybridWebViewAdvDemo.Controls;assembly=XFHybridWebViewAdvDemo"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:iOsSpecific="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
iOsSpecific:Page.UseSafeArea="true"
mc:Ignorable="d">

<ContentPage.Content>


        <!--  Place new controls here  -->

    <AbsoluteLayout>




        <StackLayout AbsoluteLayout.LayoutFlags="All"
                     AbsoluteLayout.LayoutBounds="0,0,1,1">
            <controls:HybridWebView
            x:Name="webViewElement"
            HorizontalOptions="FillAndExpand"
            VerticalOptions="FillAndExpand"
            Navigating="Browser_Navigating"
            Navigated="Browser_Navigated"/>

        </StackLayout>



        <StackLayout BackgroundColor="Aqua" AbsoluteLayout.LayoutFlags="PositionProportional" AbsoluteLayout.LayoutBounds="0.5,0.5,AutoSize,AutoSize">
            <Label Text="Başlangıç"/>
            <Label Text="Bitiş"/>
        </StackLayout>


        <ActivityIndicator x:Name="loading" IsRunning="False" IsVisible="false"/>



    </AbsoluteLayout>


</ContentPage.Content>

Mainpage.xaml.cs 代码:

Mainpage.xaml.cs code:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
    private DeviceFeaturesHelper _deviceFeaturesHelper;


    public MainPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);
        webViewElement.Source = "https://mywebsite.com/";
        webViewElement.RegisterAction(ExecuteActionFromJavascript);
        _deviceFeaturesHelper = new DeviceFeaturesHelper();



    }




    protected override void OnAppearing()
    {
        base.OnAppearing();

        //loading.IsVisible = true;
        //loading.IsRunning = true;
        //await DisplayAlert("Alert", "Uygulama açılıyor", "OK");

    }



    private void Browser_Navigating(object sender, WebNavigatingEventArgs args)
    {

        Console.WriteLine("geçiyor");

        //loading.IsVisible = true;
        //loading.IsRunning = true;

    }
    private void Browser_Navigated(object sender, WebNavigatedEventArgs args)
    {
        //loading.IsVisible = false;
        //loading.IsRunning = false;


        Console.WriteLine("geçti");

    }





    protected override bool OnBackButtonPressed()
    {
        webViewElement.GoBack();
        return true;
    }

    //sayfadaki sonuc id'si icindeki veriyi alır

    private async Task<string> tokenal()
    {
        var firebaseCek = DependencyService.Get<IFireBaseTokenService>();
        return await webViewElement.EvaluateJavaScriptAsync($"document.getElementById('token_alan').value= '{firebaseCek.GetDeviceModel()}';");
    }

    private async Task<string> deviceal()
    {
        var deviceName = DeviceInfo.Name;
        var platform = DeviceInfo.Platform;
        var device = DeviceInfo.Model;
        return await webViewElement.EvaluateJavaScriptAsync($"document.getElementById('device_alan').value= '{deviceName} - {device} - {platform}';");
    }


    private async Task<string> GetMail()
    {
        return await webViewElement.EvaluateJavaScriptAsync("document.getElementById('ozel_email').innerHTML");
    }
    private async Task<string> GetKullaniciAdi()
    {
        return await webViewElement.EvaluateJavaScriptAsync("document.getElementById('ozel_kullanici_adi').innerHTML");
    }
    private async Task<string> GetAdi()
    {
        return await webViewElement.EvaluateJavaScriptAsync("document.getElementById('ozel_adi').innerHTML");
    }
    private async Task<string> GetSoyadi()
    {
        return await webViewElement.EvaluateJavaScriptAsync("document.getElementById('ozel_soyadi').innerHTML");
    }
    private async Task<string> GetGorunenAdi()
    {
        return await webViewElement.EvaluateJavaScriptAsync("document.getElementById('gorunen_ad').innerHTML");
    }

    [Obsolete]
    private async void ExecuteActionFromJavascript(string param1, string param2)
    {


        if (param1 != null && param1.Equals("PHOTO") && param2.Equals("CAMERA"))
        {
            var result = await _deviceFeaturesHelper.TakePhoto(this);
            if (result != null)
            {
                await webViewElement.EvaluateJavaScriptAsync($"setresult_takephoto('{result}')");

            }
        }

HybridWebViewRenderer.cs

HybridWebViewRenderer.cs

[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]

命名空间 XFHybridWebViewAdvDemo.Droid.Renderers{公共类 HybridWebViewRenderer : WebViewRenderer{private const string JavascriptFunction = "function invokeXamarinFormsAction(data){jsBridge.invokeAction(data);}";上下文_context;

namespace XFHybridWebViewAdvDemo.Droid.Renderers{public class HybridWebViewRenderer : WebViewRenderer{private const string JavascriptFunction = "function invokeXamarinFormsAction(data){jsBridge.invokeAction(data);}";Context _context;

    public HybridWebViewRenderer(Context context) : base(context)
    {
        _context = context;
    }

    protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
    {
        base.OnElementChanged(e);

        Control.Settings.JavaScriptEnabled = true;
        Control.Settings.SetAppCacheEnabled(true);
        Control.Settings.CacheMode = Android.Webkit.CacheModes.Normal;
        Control.Settings.SetRenderPriority(RenderPriority.High);
        Control.Settings.DomStorageEnabled = true;
        Control.Settings.LoadsImagesAutomatically = true;

        //Control.Settings.BlockNetworkImage = true;


        if (e.OldElement != null)
        {
            Control.RemoveJavascriptInterface("jsBridge");
            ((HybridWebView)Element).Cleanup();
        }
        if (e.NewElement != null)
        {
            Control.SetWebViewClient(new JavascriptWebViewClient($"javascript: {JavascriptFunction}"));
            Control.AddJavascriptInterface(new JsBridge(this), "jsBridge");
            //// No need this since we're loading dynamically generated HTML content
            //Control.LoadUrl($@"file:///android_asset/Content/{((HybridWebView)Element).Uri}");
        }

    }

}

}

HybridWebView.cs

HybridWebView.cs

 public class HybridWebView : WebView
{



    private Action<string, string> _action;

    public void RegisterAction(Action<string, string> callback)
    {
        _action = callback;
    }

    public void Cleanup()
    {
        _action = null;
    }

    public void InvokeAction(string param1, string param2)
    {
        if (_action == null || (param1 == null && param2 == null))
        {
            return;
        }

        if (MainThread.IsMainThread)
            _action.Invoke(param1, param2);
        else
            MainThread.BeginInvokeOnMainThread(() => _action.Invoke(param1, param2));
    }



}

推荐答案

由于 ShouldOverrideUrlLoading 方法已过时,我强烈建议您使用另一种方法,例如 OnPageStarted , OnPageFinished ,OnReceivedError .

Since ShouldOverrideUrlLoading method is obsolete , I strongly recommend you to use another method like OnPageStarted , OnPageFinished ,OnReceivedError .

OnPageStarted方法中显示activityindicator,在OnPageFinishedOnReceivedError方法中隐藏它.

Show the activityindicator in OnPageStarted method , and hide it in OnPageFinished and OnReceivedError method .

为了实现它,我们可以在这里使用消息中心.

To achieve it we can use Messaging Center here .

public override void OnPageStarted(Android.Webkit.WebView view, string url, Bitmap favicon)
{
    base.OnPageStarted(view, url, favicon);

    MessagingCenter.Send<object, bool>(this, "Hi", true);
}

public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
    base.OnPageFinished(view, url);
    view.EvaluateJavascript(_javascript, null);

    MessagingCenter.Send<object,bool>(this, "Hi",false);
}

public override void OnReceivedError(Android.Webkit.WebView view, IWebResourceRequest request, WebResourceError error)
{
     base.OnReceivedError(view, request, error);
     MessagingCenter.Send<object, bool>(this, "Hi", false);
}

主页

 MessagingCenter.Subscribe<object, bool>(this,"Hi",(obj,show)=> {
     loading.IsVisible = show;
     loading.IsRunning = show;
 });

这篇关于Xamarin.Forms ShouldOverrideUrlLoading 触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 21:33