【问题标题】:Javascript Interface, error "Uncaught Error: Error calling method on NPObject"Javascript 接口,错误“未捕获的错误:在 NPObject 上调用方法时出错”
【发布时间】:2014-01-25 10:08:12
【问题描述】:

在我的 Android 应用程序中,我使用 WebAppInterface 从 Javascript 桥接到 Java。

我的 .html 文件包含一些运行“Android.canPlay();”的 JS在某些时候。

在我的应用中,函数“canPlay()”会触发变量监听器。

当变量侦听器触发时,如果满足条件,一些文件会被重命名(临时文件,下载时带有 .tmp 附加扩展名,包括 .html 文件(因此它是 .html.tmp,带有原始 . html 存在于它旁边))

重命名发生后,Web 视图被重新加载(我尝试过同时使用函数和“.loadUrl()” - 两者都会出错)

当需要在 webview 中重新加载 html 文件时,出现错误:

E/Web 控制台:未捕获的错误:在 NPObject 上调用方法时出错。在 file:////mnt/sdcard/Download/qwerty/playlists/29/2/index.html:206

第 206 行是“Android.canPlay()”调用。

注意事项 - 如果我在重新加载 webview 之前不重命名文件,而是从运行的后台服务重命名,我没有这个错误(尽管我确实得到了一个关于在 WebViewCoreThread 上运行的东西)

一些代码:

WebApp接口

public class WebAppInterface {
    final Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void canPlay()
    {
        mPlaylistReady.changeState(true);
    }
}

变量侦听器(通过侦听器类触发)(删除了一些代码,例如文件位置的共享首选项)

@Override
public void onStateChange(boolean state) {

    if (state) { // true
            // this finds all the files and removes the .tmp extension
            fileRenamer.removeTmp(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/qwerty/playlists/"));

            // reloads the webview
            WebViewActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    webView.loadUrl("file:///" + htmlFile.getAbsolutePath());
                }
            });

        }
    }
}

文件重命名器类

public class FileRenamer {

    public void removeTmp(File directory)
    {
        File dir = directory;
        if(dir.isDirectory()) {
            for(File child : dir.listFiles()) {
                String name = child.getName();
                String ext = name.substring(name.lastIndexOf('.'));
                if(ext.equals(".tmp")) {
                    final int lastPeriodPos = name.lastIndexOf('.');
                    File renamed = new File(dir, name.substring(0, lastPeriodPos));
                    child.renameTo(renamed);
                }
            }
        }
    }

}

【问题讨论】:

  • 澄清一下 - canPlay 最初是通过 JavaScript 工作的,只有在重新加载后才停止工作?
  • 没关系,我解决了这个问题,把文件重命名类变成了一个 AsyncTask :)

标签: android android-webview android-file android-jsinterface


【解决方案1】:

这个错误是由 JavaScript 抛出的,因为在 Java canPlay() 实现过程中发生了异常。

尝试将 WebAppInterface.canPlay() 方法封装在 try-catch 子句中并记录异常以找出可能发生的情况。

除此之外,我正在尝试寻找一种在 JavaScript 上下文中映射异常的方法,但恐怕这是不可能的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    相关资源
    最近更新 更多