Amit Aisikowitz
Amit Aisikowitz

Reputation: 143

Nativescript webview and android back button

I have a made a page in nativescript that only containes a webview. Here is my code:

<Page xmlns="http://www.nativescript.org/tns.xsd" actionBarHidden="true">

    <WebView src="http://example.com/" />

</Page>

And here is the JS:

import * as webViewModule from "tns-core-modules/ui/web-view";

let webView = new webViewModule.WebView();

webView.on(webViewModule.WebView.loadFinishedEvent, function (args: webViewModule.LoadEventData) {
    let message;
    if (!args.error) {
        message = "WebView finished loading " + args.url;
    }
    else {
        message = "Error loading " + args.url + ": " + args.error;
    }

});
webView.src = "http://example.com/";

Everything is working great until I press the android back button. Then inside of navigating to the last page inside the webview, the app just exists. When I open it again from the applications menu (returning to the same minimized app) it reloads the webview content and not saving it's state.

Help will be appreciated.

Upvotes: 5

Views: 2477

Answers (1)

Deepika
Deepika

Reputation: 460

You need to handle Android hard button like this:

First import dependencies :

import { AndroidApplication, AndroidActivityBackPressedEventData } from "application";
import * as application from "application";

Then add this code :

application.android.on(AndroidApplication.activityBackPressedEvent, (data: AndroidActivityBackPressedEventData) => {
  data.cancel = true; // prevents default back button behavior
  console.log("webview can go back " + webView.canGoBack);
  if (webView.canGoBack) //if webview can go back
      webView.goBack();
  else
      this.router.backToPreviousPage();
});

Upvotes: 9

Related Questions