如何使用 JSNI 从 GWT Java 运行 JavaScript 函数? [英] How to run JavaScript function from GWT Java with JSNI?
问题描述
无法从手册中理解:如何从 Java 中实际运行 JS 函数?
Can't understand from the manual: how actually to run JS function from Java?
例如,我的 html 页面中有一个函数:
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();
}-*/;
}
手册中说,在嵌套框架内实现的原生函数,解释了这种情况.那么如何运行JS函数呢?
It is said in manual, that native functions implemented within nested frame, which explains the situation. But how to run JS functions then?
更新 1以下作品.
Java:
public static native void fooRunner() /*-{
$doc.fooRunner();
}-*/;
JS:
<script type="text/javascript" language="javascript">
document.fooRunner = function foo() {
alert('Foo!');
}
</script>
有更好的方法吗?
推荐答案
您自己回答了问题.没有更好的方法,原因很简单:部署 GWT 应用程序有多种方法,在 iframe 中运行只是其中一种选择.所以这就是为什么你必须使用 $wnd 变量来访问外部 JS 函数的原因,所以如果你切换链接器,你的静态代码将正常工作.
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.
这篇关于如何使用 JSNI 从 GWT Java 运行 JavaScript 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!