Fernando Mondo
Fernando Mondo

Reputation: 477

Webview Session Storage lost when navigate between Xamarin pages

I have a Xamarin.Forms App with Two Pages, one with a WebView and other with just text.

Session Storage lost data when I navigate between pages.

//APage.xaml

<WebView x:Name="webView" WidthRequest="1000" HeightRequest="1000" Navigated="webView_Navigated">
  <WebView.Source>
    <UrlWebViewSource />
  </WebView.Source>
</WebView>

//BPage.xaml

<Span Text="Hi B Page"/>

//APage.xaml.cs

...

 public BPage()
  {
            InitializeComponent();

            (webView.Source as UrlWebViewSource).Url = "mytestsite.com";

  }

private async void webView_Navigated(object sender, WebNavigatedEventArgs e)
  {
            var webView = sender as WebView;
          
            var token = await webView.EvaluateJavaScriptAsync("window.sessionStorage.getItem('token')");

            System.Console.WriteLine(token); //Every time I Go to BPage and back, it is null.
  }

My website return a "Token not found in sessionstorage" error.

Upvotes: 0

Views: 534

Answers (1)

nevermore
nevermore

Reputation: 15796

//Every time I Go to B Page and back, it is null.

When you navigate from B to A, page B will be released and every time you navigate from A to B, you are navigating to a new PageB(not the same PageB every time).

Each webView you use is under different Page B and that's why you get null.

Here is the document about Navigation.

You can use Xamarin.Essentials: Preferences to save token in apps.

Save:

Preferences.Set("my_key", "my_value");

Read:

var myValue = Preferences.Get("my_key", "default_value");

Upvotes: 1

Related Questions