Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Javascript execution in Android Webview

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();
like image 363
Vivek Avatar asked Jul 30 '14 17:07

Vivek


1 Answers

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

like image 57
VERT9x Avatar answered Oct 03 '22 10:10

VERT9x