Skip to content Skip to sidebar Skip to footer

Gwt And Jsni Add Javascript Button Into Html Panel

I create a simple Javascript file containing a simple button. function testfuncion() { document.write(''); } Then I creat

Solution 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 voidtestfunction() /*-{
  $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.

Solution 2:

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

publicclassMyInputHtmlextendsHTML {

    publicMyInputHtml() {

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

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

    privatenativevoidtestfunction()/*-{
        $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.

Solution 3:

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

Post a Comment for "Gwt And Jsni Add Javascript Button Into Html Panel"