Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling JavaScript from Android

I am having trouble calling basic JavaScript functions from within Android. When I cloned the repository from this tutorial, and then stripped it down I was able to get the code to function correctly. However, when trying to create my own fresh project I have been unsuccessful.

I have referenced the following posts and appear to be doing the same, but to no avail. There is no noticeable different between the approaches, so I feel like there may be dependencies outside of these files that I am missing?

Android Calling JavaScript functions in WebView

Run javascript code in Webview

I'm wondering if I am missing something subtle somewhere.

Basically I am just trying to get any output to the console by calling a JavaScript function that is defined in its own file. The project structure is as follows:

main
- assets
  - index.html
  - sketch.js

- java
  - com.mypackage
    - MainActivity.java

I have a file sketch.js with the following function inside

function hello() {
    console.log("hello world");
}

And an index.html file with the following code

<!DOCTYPE html>
<html>
  <head>
    <script src="sketch.js" type="text/javascript"></script>

  </head>
  <body>
  <canvas></canvas>
  </body>
</html>

Then from my activity class I have the following Java code

webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("file:///android_asset/index.html");

webView.evaluateJavascript("javascript:hello();", null);
webView.evaluateJavascript("console.log('Hello world 2');", null);

In the console in Android Studio I see

[INFO:CONSOLE(1)] "Uncaught ReferenceError: hello is not defined", source:  (1)
I/chromium: [INFO:CONSOLE(1)] "Hello world 2", source:  (1)

How can I fix this code to be able to call the simple JavaScript function hello() that is in a separate file?

like image 259
btin Avatar asked Oct 28 '18 04:10

btin


1 Answers

According to CW answer,

You need to wait until your page is loaded

private void helloJs(){
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        webView.evaluateJavascript("javascript:hello();", null);
    } else {
        webView.loadUrl("javascript:hello();");
    }
}

webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        helloJs();
    }
});
like image 55
Khaled Lela Avatar answered Sep 22 '22 03:09

Khaled Lela