Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 390
Amit Aisikowitz Avatar asked Feb 06 '18 15:02

Amit Aisikowitz


1 Answers

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();
});
like image 118
Deepika Avatar answered Nov 11 '22 11:11

Deepika