GWT and JSNI add Javascript button into HTML panel

只谈情不闲聊 提交于 2019-12-24 04:01:28

问题


I create a simple Javascript file containing a simple button.

function testfuncion() {
    document.write('<input type="button" name="hello" value="hello">');
}

Then I created a HTML panel in gwt.

HTML panelHtmlTry = new HTML();

How can put the Javascript button into the HTML panel?

In this experiment I can't create the button in gwt but only put a Javascript object into the gwt panel.

PS: i can use html panel or horizzontal panel. My objective is put a javascript button on each GWT panel and show it


回答1:


Yeah, there is a simpler way to do what you want. But if you want to do what you want. You can call the custom JavaScript method through JSNI.

This JSNI method calls your custom JS script, which is included in the host page.

private native void testfunction() /*-{
  $wnd.testfuncion();
}-*/;

$wnd is a reference to the browsers window object see GWT Docs on JSNI

Then you can call this JSNI method anywhere in your GWT code:

testfunction();

And every time, the JavaScript function from the file gets called through JSNI.


You can temporarily redifine document.write, so that it sets the button in the HTML widget you wish.

private native void testfunction(HTML html) /*-{
  var originalWriteFunc = $wnd.document.write;
  $wnd.document.write = function(str) {
    html.@com.google.gwt.user.client.ui.HTML::setHTML(Ljava/lang/String;)(str);
  };

  $wnd.testfuncion();
  $wnd.document.write = originalWriteFunc;
}-*/;

So you need to call testfunction, with the HTML widget, where the button should be positioned.




回答2:


Given that no modifications are allowed to the JS file, and assuming the input is the only input in the document, you could extend HTML to wrap the input element:

public class MyInputHtml extends HTML {

    public MyInputHtml() {

        // initialize DOM with external script content
        testfunction();

        // set the DOM element as the widget's element
        Element body = RootPanel.get().getElement();
        Element el = body.getElementsByTagName("input").getItem(0);
        setElement(el);
    }

    private native void testfunction() /*-{
        $wnd.testfuncion();
    }-*/;
}

It'll be best, of course, if you assign the input with an id. That way you can look it up simply by calling RootPanel.get(id), thus avoiding the need for an index based search. This will robust your code, as changes in the DOM won't affect this lookup.




回答3:


Let your testFunction return a string. This you can insert into your panelHtmlTry.



来源:https://stackoverflow.com/questions/14089810/gwt-and-jsni-add-javascript-button-into-html-panel

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