简体   繁体   English

Android WebView - 检测是否定义了一个JS function

[英]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).我正在编写一个在 Android 上的 WebView 下运行的 HTML/JS 应用程序。在某些情况下,可能无法加载包含该应用程序的页面,或者可能会加载另一个页面(例如 404 页面或类似页面)。 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.通常,我需要在应用程序页面上运行一组 JS 函数或采取另一组操作以防应用程序页面未加载。

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 .我试图通过检测适当的 JS 是否可用来检测是否已加载正确的页面,但我似乎无法找到任何同步方式 - 只能通过调用 JS function 并期望通过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.我当然不能通过分析页面的 URL 来做到这一点——它可能是正确的,但内容有误。

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".更新:此代码将检查由“typeof”定义的 JS function,并通过 javascript 接口“onLoaded”将其结果返回给 java。

I think you can do it, Please look at PhoneGap project, you will find your answer.我认为你可以做到,请查看PhoneGap项目,你会找到答案。

PhoneGap is an awesome free framework for mobile platform. PhoneGap 是一个很棒的移动平台免费框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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