简体   繁体   English

Android WebView JavascriptInterface属性

[英]Android WebView JavascriptInterface Property

Hey I am working with an app that has to interface with some javascript (coffeescript) code. 嘿,我正在使用必须与一些javascript(咖啡)代码交互的应用程序。 The code JS code looks something like this: JS代码看起来像这样:

$(".content").on "click", ".feedback", ->
      window.webkit.foo.bar.message("hello")
      false

So I need to add a javascript interface to my WebView like: 所以我需要向我的WebView添加一个javascript界面​​,例如:

 webView.addJavascriptInterface(new Window(), "window");
 ...
 class Window {
   @JavascriptInterface
   public Webkit webkit() {
     return new Webkit();
   }
   class Webkit {
     @JavascriptInterface
     public Foo foo() {
 ...

I am running into two problems here, first it appears you can't add properties to the global window object. 我在这里遇到两个问题,首先,您似乎无法向全局窗口对象添加属性。 And second when I change my interface name to something else, I can't seem to figure out how to add properties rather than methods. 其次,当我将接口名称更改为其他名称时,我似乎无法弄清楚如何添加属性而不是方法。

I can get it to work in a way like this: 我可以使它以这种方式工作:

  webkit().foo().bar().message("hello")

Has anyone done anything like this? 有人做过这样的事情吗?

Thanks! 谢谢!

The window object in browsers (and in WebView) already has a window property, which points back to the same object. 浏览器(和WebView)中的window对象已经具有window属性,该属性指向相同的对象。 Try evaluating this in your JavaScript debugger console: 尝试在JavaScript调试器控制台中对此进行评估:

> window.window === window
< true

So trying to inject a Java object with a name "window" would produce confusing results and may break code, since you will likely break this invariant. 因此,尝试注入名称为"window"的Java对象将产生令人困惑的结果,并且可能会破坏代码,因为您可能会破坏此不变式。

And it is also true that Java Bridge only exposes function objects through properties, it doesn't support exposing getters or setters. 确实,Java Bridge仅通过属性公开函数对象,不支持公开getter或setter。 Though, you can overcome that with a bit of JavaScript magic by defining getters and setters yourself. 不过,您可以通过自己定义getter和setter来使用JavaScript魔术来克服这一问题。 You will need to expose getter and setter methods on your injected object and then assign them to be property getter setters with JavaScript. 您将需要在注入的对象上公开getter和setter方法,然后使用JavaScript将它们分配为属性getter setter。

So, in Java you name method differently, eg: 因此,在Java中,您对方法的命名不同,例如:

webView.addJavascriptInterface(new Window(), "myWindow");

class Window {
  @JavascriptInterface
  public Webkit getWebkit() {
    return new Webkit();
  }
  ...

And then after you have loaded the page, you can execute JavaScript code like this: 然后,在加载页面之后,可以执行如下的JavaScript代码:

Object.defineProperty(myWindow, 'webkit', { get: myWindow.getWebkit });

Then both calling getWebkit() and accessing webkit on myWindow will mean the same thing. 然后,调用getWebkit()和访问myWindow webkit都具有相同的含义。

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

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