如何使用 JSNI 从 GWT Java 运行 JavaScript 函数?
从手册中无法理解:实际上如何从Java运行JS函数?
例如,我的html页面中有一个函数:
<script type="text/javascript" language="javascript">
function foo() {
alert('Foo!');
}
</script>
下面的模块显示了两个按钮,只有第二个按钮起作用:
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函数呢?
更新1 以下作品。
Java:
public static native void fooRunner() /*-{
$doc.fooRunner();
}-*/;
JS:
<script type="text/javascript" language="javascript">
document.fooRunner = function foo() {
alert('Foo!');
}
</script>
有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你自己回答了你的问题。没有更好的方法,原因很简单:部署 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.