2

I have a function defined in a .js file, which is included in the main .html file with this code:

<script type="text/javascript" language="javascript" 
    src="js/script.js"></script>

I also have a JSNI method that invokes a function that is defined in the js file:

public native void addJsModule(String name) /*-{
        addNewSection(name);
    }-*/;

When I invoke the java method, I get this exception:

com.google.gwt.event.shared.UmbrellaException: Exception caught: Exception caught: (ReferenceError) @client.registros.home.RegistyHome::addJsModule(Ljava/lang/String;)([string: 'acercade']): addNewSection is not defined

Thanks!!

jigarzon
  • 1,208
  • 2
  • 12
  • 28

2 Answers2

4

GWT code runs (by default) in a hidden iframe, where your script is not available. There's a $wnd variable referencing the Window object of the enclosing browsing context (where your script has been loaded). You therefore have to prefix your function with $wnd to reference the function as defined in the outer browsing context:

public native void addJsModule(String name) /*-{
    $wnd.addNewSection(name);
}-*/;

See http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html#writing

Note that the code did not reference the JavaScript window object directly inside the method. When accessing the browser’s window and document objects from JSNI, you must reference them as $wnd and $doc, respectively. Your compiled script runs in a nested frame, and $wnd and $doc are automatically initialized to correctly refer to the host page’s window and document.

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
1

You have to make your javascript-method available by storing it in a shared object.

A commonly used construct is to store the method in $doc. In JavaScript save your method like this:

document.addNewSection = new function(name) {addNewSection(name);};

Afterwards use it in the jsni-body of your GWT native method like this:

$doc.addNewSection(name);

(you can also use JSNI $wnd with JS window, if you want)

See also:

Community
  • 1
  • 1
slartidan
  • 20,403
  • 15
  • 83
  • 131
  • Thanks. I added this code: document.addNewSection = new function(name) { addNewSection(name); }; And I'm still getting this exception: $doc.addNewSection is not a function – jigarzon Jul 22 '15 at 16:42
  • try `document.addNewSection = new function (name) { alert ('call received in Javascript'); };` and tell us, whether you see a popup. – slartidan Jul 22 '15 at 19:20