Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView canGoBack always true

I have a WebView that is loading social media pages. I have overridden the Back button to call the goBack method on the WebView until canGoBack() returns false. Then it calls super.onBackPressed(). The problem is that Twitter and YouTube use Javascript in such a way that canGoBack() returns true unless you tap the back button 4 times really quickly.

I've tried checking the original url with the current url, but the page has a different url than the one that gets passed in.

Does anyone know a way to have the back button call the WebView's goBack method until you are at the beginning, then call super.onBackPressed?

like image 748
toadzky Avatar asked Mar 18 '26 17:03

toadzky


2 Answers

Well, it's not ideal but you may track the navigation history manually by using an array (or just an integer to be increased and decreased) and push the current url into it every time it changes and pop the last url from it when you press the back button, and if the array is empty (or the integer is 0) you call super.onBackPressed().
To execute code when the url changes, you can override the method boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) of the WebViewClient (link to the documentation).
This way the web pages' javascript can't interfere with how you handle the back button.

like image 102
nonzaprej Avatar answered Mar 20 '26 06:03

nonzaprej


I had similar problem, but in my case the problem was that I, when overriding the WebViewClient's shouldOverrideUrlLoading(), I checked if the url was the correct one, and if it was I was loading that url in my webView and returning false after that which shouldn't be done. So I just returned false and it started working correctly. Hope I helped someone.

like image 24
Naum Djordjevic Avatar answered Mar 20 '26 07:03

Naum Djordjevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!