How to run JavaScript function from GWT Java with JSNI? [duplicate]

家住魔仙堡 提交于 2019-11-28 07:25:42

问题


This question already has an answer here:

  • How to call GWT java function from Javascript? 1 answer

Can't understand from the manual: how actually to run JS function from Java?

For example, I have a function in my html page:

<script type="text/javascript" language="javascript">
    function foo() {
        alert('Foo!');
    }
</script>

The following module shows two buttons, only second of which works:

public class Test_GoogleWeb_JSNI_01 implements EntryPoint {

public void onModuleLoad() {

    Button fooButton = new Button("Foo!");
    fooButton.addClickHandler(new ClickHandler(){
        public void onClick(ClickEvent event) {
            fooRunner();
        };
    });


    HTML fooButtonNative = new HTML();
    fooButtonNative.setHTML("<input type='button' value='Foo Native' onclick='foo()'>");

    RootPanel rootPanel = RootPanel.get();
    rootPanel.add(fooButton);
    rootPanel.add(fooButtonNative);

}

public static native void fooRunner() /*-{
  foo();
}-*/;
}

It is said in manual, that native functions implemented within nested frame, which explains the situation. But how to run JS functions then?

UPDATE 1 The following works.

Java:

public static native void fooRunner() /*-{
  $doc.fooRunner();
}-*/;

JS:

<script type="text/javascript" language="javascript">
    document.fooRunner = function foo() {
        alert('Foo!');
    }
</script>

Is there a better way?


回答1:


You answered your question yourself. There is no better way for a very simple reason: there are multiple ways to deploy GWT app, running in iframe is only one of the options. So that's why you have to use $wnd variable to access external JS function, so in case if you switch the linker , your still code will work just fine.



来源:https://stackoverflow.com/questions/8617055/how-to-run-javascript-function-from-gwt-java-with-jsni

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!