Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the native back button event from within webview

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?

like image 289
Ivin Avatar asked Aug 24 '15 19:08

Ivin


People also ask

How do you handle back button in flutter WebView?

To get a callback when we press the back button, we need to wrap our view inside WillPopScope and create a method inside _WebViewWebPageState to check if webview can go back. If it can, then we perform the back operation. Otherwise, we'll show exit dialog.

How do I go back in WebView react native?

refs[WEBVIEW_REF]. goBack(); return true; } }); }; onNavigationStateChange = (navState) => { this. setState({ backButtonEnabled: navState. canGoBack, }); };

What is a native WebView?

A WebView is just the browser engine part that you can insert sort of like an iframe into your native app and programmatically tell it what web content to load. Putting all of this together and connecting some dots, a WebView is just a visual component/control/widget/etc.


2 Answers

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.

like image 84
Reed Spool Avatar answered Nov 07 '22 13:11

Reed Spool


You could try mixing some question and their solutions:

  1. Intercept the back button tap event in Android

  2. Exec a js function inside the webview (from the outside)

  3. That will trigger an event in the document

  4. Listen to this event using document.addEventListener and here close your dialog/alert

like image 30
lifeisfoo Avatar answered Nov 07 '22 12:11

lifeisfoo