Why my app is crashing when OnBackPressed is called?

Viewed 418

I'm trying to execute some javascript(webview Eval) when back button(OnBackPressed) is pressed but the app crashs. Can someone figure out what is happening?

MainActivity.cs

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        /*
     some code
    */
        base.OnCreate(savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        LoadApplication(new App());
    }

    public override void OnBackPressed()
    {
        MainPage.ExecJS();
}
}

MainPage.xaml.cs

 public partial class MainPage : ContentPage
 {
    public static double ScreenWidth { get; set; }
    public static double ScreenHeight { get; set; }
    public static WebView webnav;
    StackLayout parent = null;
    public MainPage()
    {
        InitializeComponent();
        WebView webnav = new WebView
        {
            HeightRequest = 1000,
            WidthRequest = 1000,
            Source = "https://www.comprarmusicas.com.br/mobile/index.php"
        };
        parent = new StackLayout();
        parent.Children.Add(webnav);
        Content = parent;
    }

     public static void ExecJS()
    {
        string jsCode = "alert('ok');";
        webnav.Eval(jsCode);
    }
 }
1 Answers

You are not assigning the static WebView variable in your .ctor but creating a new local instance variable.

Remove the WebView type from where you instance/assign the WebView, ie.

public MainPage()
{
    InitializeComponent();
    webnav = new WebView // this assigns to the "public static WebView webnav;"
    {
        HeightRequest = 1000,
    ~~~
Related