简体   繁体   中英

Android WebView - detect whether a JS function is defined

I'm writing an HTML/JS application that runs under a WebView on Android. Under certain circumstances the page containing the application may not be loaded, or another page might instead (such as 404 page or similar). In general, I need to run a set of JS functions on the application page or take another set of actions in case the application page didn't load.

I'm trying to detect whether the proper page has loaded by detecting whether the appropriate JS is available, but I can't seem to find any way to do it synchronously - only by calling a JS function and expecting a callback via JavasctiptInterface . While this method is feasible, I'm wondering whether there is a better, more elegant and reliable way to accomplish this.

I certainly can't do this by analyzing the page's URL - it might be the right one but with a wrong content.

Any ideas?

@JavascriptInterface
public void onLoaded(String result) {
    if (result.equals("function")) {
        // defined
    } else {
       // not defined
    }
}

private void checkJSFunction() {
    loadUrl("javascript:yourJSInterfaceName.onLoaded(typeof yourFunctionName)");
}

update : this code will check the JS function define by "typeof" and return its result to java through javascript interface "onLoaded".

I think you can do it, Please look at PhoneGap project, you will find your answer.

PhoneGap is an awesome free framework for mobile platform.

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