'Can I call function from previously loaded javascript on android WebView?

I'm loading javascript into a WebView from the Activity, the webpage being shown is external. The problem is that I'm not able to call a fucntion that I've previously loaded, neither access variables values. When I do webView.loadUrl("""var a = 0; function foo(){a = 1;}""") the code executes perfectly (this code is only an example). But if I then do webView.loadUrl("""foo();""") It gives an "foo not defined" error. And yes, I'm loading the js after the page has finished loading.



Solution 1:[1]

Have you called setJavaScriptEnabled(true).

Also, have you tried loading the function like this

webView.loadUrl(
            """javascript:(function() {
            // my js code
            })()"""
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 peshkira