Reputation: 4815
Im new to webviews and trying to do an app using it. I have a popup that is displayed using javascript. It has a close button to close. Along with the close button, I want to make use of the native back button.
That is, if user clicks the back button, my popup should be closed.
My doubt is, does it require any changes from native app? Or the webviews convert the back button action to some events like keypress that the webview can understand?
Upvotes: 7
Views: 6467
Reputation: 2781
To further aid what lifeisfoo
stated:
public class WebViewer
WebView webView;
@Override
public void onBackPressed() {
if (webView.hasPopUp()) {
webView.loadUrl("javascript:closePopUp()");
} else {
super.onBackPressed();
}
}
Upvotes: 1
Reputation: 41665
Clicking backbutton would close your viewcontroller which shows the modal.
I guess you don't want that happen, and just close the javascript modal.
Yes you would need to change your native code.
On native backbutton click,
if your modal is open:
close the modal
else:
do default backbutton action.
Below is a detailed explanation.
On native backbutton click # your native code to intercept the back button
if your modal is open:
# there are multiple options here
# first strategy
# let javascript inform native side when it opens/closes popup
# native just needs to check the status he has
# second strategy
# native asks javascript if he has a modal open
# this is a bit tricky because native can't get a return value from javascript
# native asks javascript to tell native if he has a modal open (native->javascript + javasciprt -> native two function calls)
# native checks what javascript just said
close the modal
# this is easy, ask javascript to close it.
I assumed you know how to communicate between javascript & native, if not take a look at http://www.smashingmagazine.com/2013/10/best-of-both-worlds-mixing-html5-native-code/
Upvotes: 1
Reputation: 16294
You could try mixing some question and their solutions:
Intercept the back button tap event in Android
Exec a js function inside the webview (from the outside)
That will trigger an event in the document
Listen to this event using document.addEventListener
and here close your dialog/alert
Upvotes: 2
Reputation: 843
I don't know if you have HTML5 support, but if so history.pushState
and history.onpopstate
from the History API will do exactly what you want.
When the popup is displayed, use pushState
to inform the browser of a new history entry, same as if the popup was instead a new page.
Then add an event listener to history.onpopstate
which closes the popup, if it's open.
Upvotes: 2
Reputation: 144
If you are using Cordova, it offers an event to track the back button on Android devices:
document.addEventListener("backbutton", yourCallbackFunction, false);
You can override this event and implement your own behaviour. Other than this there is should not be a way to track the back button event.
Upvotes: 1