Reputation: 1843
Scenario: I have an activity containing a WebView. Every time I start that activity, some HTML content is being rendered inside the WebView. I am also injecting Javascript in WebView which has some code including DomContentLoaded event listener.
Problem: The problem is that sometimes Javascript is taking lot of time to execute in WebView. This happens randomly not every time. Most of the time it loads up very fast. But sometimes for the same content it takes >20 seconds to execute. Now in this state if I go back from the activity and start it again, Javascript will not load in WebView as the previous JS execution is not yet finished. I have to kill the app and start it again in order to make the WebView work. How to recover from this state without killing the app? I tried to stop it using the following code but none of them worked. Any other suggestions?
webView.stopLoading();
webView.loadData("", "text/html", null);
webView.freeMemory();
webView.removeAllViews();
webView.destroy();
Upvotes: 11
Views: 13127
Reputation: 157
You can use GoBack()
to stop execution of all javascript (you'll literally leave that page) and GoForward()
to load old content without reloading whole page, which could cause data loss
Upvotes: 0
Reputation: 12759
Google says in docs: https://developer.android.com/reference/android/webkit/WebView.html#clearView()
Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript).
WebView.loadUrl("about:blank")
Upvotes: 1
Reputation: 372
You could try turning off Javascript temporarily and then turn it back on like this:
webview.getSettings().setJavaScriptEnabled(false);
webview.getSettings().setJavaScriptEnabled(true);
But if you're trying to clean up resources in a WebView the documentation states:
Use WebView.loadUrl("about:blank") to reliably reset the view state and release page resources (including any running JavaScript).
http://developer.android.com/reference/android/webkit/WebView.html#clearView%28%29
Upvotes: 5