本文介绍了Android WebView - 检测是否定义了 JS 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个在 Android 上的 WebView 下运行的 HTML/JS 应用程序.在某些情况下,可能不会加载包含应用程序的页面,或者可能会加载另一个页面(例如 404 页面或类似页面).一般来说,我需要在应用程序页面上运行一组 JS 函数,或者在应用程序页面未加载的情况下采取另一组操作.

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.

我正在尝试通过检测适当的 JS 是否可用来检测是否加载了正确的页面,但我似乎找不到任何同步方法 - 只能通过调用 JS 函数并期望通过以下方式进行回调JavasctiptInterface.虽然这种方法可行,但我想知道是否有更好、更优雅、更可靠的方法来实现这一点.

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.

我当然不能通过分析页面的 URL 来做到这一点 - 它可能是正确的,但内容有误.

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

有什么想法吗?

推荐答案

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

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

更新:此代码将检查typeof"定义的JS函数,并通过javascript接口onLoaded"将其结果返回给java.

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

这篇关于Android WebView - 检测是否定义了 JS 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 09:17