How to stop Javascript execution in Android Webview

Scenario: I have an activity containing a WebView. Every time I start this activity, some HTML content is displayed inside the WebView. I also inject Javascript into a WebView that has some code, including a DomContentLoaded event listener.

Problem: The problem is that Javascript sometimes takes a long time to execute in WebView. This does not happen randomly every time. Most of the time it loads very fast. But sometimes it takes> 20 seconds for the same content to complete. Now in this state, if I return from the activity and run it again, Javascript will not load in the WebView, since the previous JS execution has not been completed yet. I need to kill the application and run it again to make WebView work. How to recover from this condition without killing the application? 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(); 
+8
javascript android android-activity android-webview
source share
2 answers

You can try disabling Javascript temporarily, and then enable it as follows:

  webview.getSettings().setJavaScriptEnabled(false); webview.getSettings().setJavaScriptEnabled(true); 

But if you are trying to clear resources in WebView, the documentation says:

Use WebView.loadUrl ("about: blank") to reliably reset to view the status and resources of the release page (including any JavaScript running).

http://developer.android.com/reference/android/webkit/WebView.html#clearView%28%29

+3
source share

Google says in the docs: https://developer.android.com/reference/android/webkit/WebView.html#clearView ()

Use WebView.loadUrl ("about: blank") to reliably reset to view the status and resources of the release page (including any JavaScript running).

 WebView.loadUrl("about:blank") 
0
source share

All Articles