简体   繁体   中英

JS ReferenceError on Android WebView for api level 15

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 ?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM