简体   繁体   English

如何在Android中将嵌套对象添加为JavascriptInterface?

[英]How to add a nested object as a JavascriptInterface in Android?

I need to call a website that has some javascript in it in a WebView . 我需要在WebView调用一个包含一些JavaScript的网站。 The javascript calls a method in a nested object like this: javascript会像这样在嵌套对象中调用方法:

window.plugins.anObject.method();

and I need to intercept that call to method() and do something, when its called (ie a native implementation for method() in Java). 并且我需要拦截对method()调用,并在调用该method()时做一些事情(即Java中method()的本机实现)。 Without that plugins object, I would just do 没有那个plugins对象,我会做

myWebView.addJavascriptInterface(new Object() {
    @JavascriptInterface
    public void method() {
        // yay!
    }
}, "anObject");

but as I wrote, anObject must be a child of another plugins object. 但正如我所写, anObject必须是另一个plugins对象的子代。 So what I tried was to replace "anObject" by "plugins.anObject" but that doesn't work. 因此,我尝试用"plugins.anObject"替换"anObject" ,但这不起作用。 Is there any way how I can achieve this? 有什么办法可以实现呢?

Instand of use: 使用说明:

window.plugins.anObject.method();

may be you can try this: 也许你可以试试这个:

webview code: 网络视图代码:

myWebView.addJavascriptInterface(new Object() {
    @JavascriptInterface
    public void anObject() {
        return new Object(){
             @JavascriptInterface
             public void method() {
                 //yay!
             }
        }
    }
}, "plugins");

js code : js代码:

window.plugins.anObject().method();

Note: 注意:

the NPObject return to your js is not a common javascript object at all,you can't iterate this object and you can't redefine your member function when you define in webview such as bellow: 返回到js的NPObject根本不是一个通用的javascript对象,您无法迭代该对象,并且在webview(例如下面)中定义时无法重新定义成员函数:

$(function(){
var old_method = window.plugins.method;
window.plugins.method = function(){
    //do some thing
    old_method();
    //do another thing
};
});

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

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