JS ReferenceError on Android WebView for api level 15

467 views Asked by At

I'm trying create a web app for Android using WebView. My cenary is very simple, I have a index.html file with a button:

<button id="connect-button" onclick="connect">Connect</button>

and a simple (script) element:

<script>
connect = function () {
   alert("Oi");
};
</script>

On Android side I have an Activity to load this file on Webview

WebView web;
web = (WebView) findViewById(R.id.webview01);

//ProgressBar related to the xml
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
progressBar.setMax(100);

web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new MyWebViewClient());
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setLoadWithOverviewMode(true);
web.getSettings().setUseWideViewPort(true);
web.loadUrl("file:///android_asset/index.html");

For api level 19 or above everything works fine. But for api level 15 to 18 webview can't load my simple javascript method "connect".

I search a lot about problems with webview for api level bellow 19, but this is very simple test. Some one sometime make some thing similar to api 15 ?

1

There are 1 answers

0
Rafael Pacheco On

Solved

For my case the problem is that aparently WebView for APIs lower than 19 you must put any code explicitly on "window" object.

So, when I change my java script to

<script>
window.connect = function () {
   window.alert("Oi");
};
</script>

everything works!

We have a lot of questions similar to this problem, if this not work for you check also: