Calling Javascript function of .js file from java GWT code

15,752

Solution 1

since your code should not depend on the gwt linker (and how it loads code) you need to prefix the call with the right window object. Reapp does not take that into account. So it actually needs to be:

public static native void onMyButtonClick() /*-{
    $wnd.myJSfunction();
}-*/;

Solution 2

  1. Import the JS Lib in your .html file.
  2. Create a method like this:

    public static native void onMyButtonClick() /*-{
        myJSfunction();
    }-*/;
    
  3. Bind your button like this:

    myButton.addClickHandler(new ClickHandler() {
    
        @Override
        public void onClick(ClickEvent event)
        {
            onMyButtonClick();
        } 
    
    });
    
  4. Done!

Just make sure that the javascript containing your function is loaded before the generated GWT javascript.

Your welcome!

Share:
15,752
Manann Sseth
Author by

Manann Sseth

Developers never RIP.. We just get Garbage Collected..!! #Eat #Sleep #Code #Repeat

Updated on June 14, 2022

Comments

  • Manann Sseth
    Manann Sseth almost 2 years

    I have one button in Java GWT code. And I have one javascript file in scripts folder. I want to access functions of that js file on Button click.

    So how can I call that method from Java GWT code(Button's click event)..?

    Can anyone please tell me code or way for accessing js file's function.

    Thanks in Advance.

  • Daniel Kurka
    Daniel Kurka over 11 years
    this will not work with some linker since the global window object (in which you are looking up myJSfunction) might not be the same window object. (gwt can load code in an hidden iframe...)
  • Racing Tadpole
    Racing Tadpole about 9 years
    If you're wondering about the unusual commenting in this code, or why you need $wnd, check out GWT's JavaScript Native Interface (JSNI) docs for more details.