Mohamed Gamal
Mohamed Gamal

Reputation: 139

Call external JavaScript located inside iframe from java code using jsni

I am trying to call JavaScript method from Java using the following code

native void notifyJs() /*-{
    $wnd.foo();
}-*/;

The JavaScript method is located inside iframe and looks like

function foo() {
    alert("Do something");
}

But I am receiving this error

SEVERE: (TypeError) : $wnd.foo is not a functioncom.google.gwt.core.client.JavaScriptException: (TypeError) : $wnd.foo is not a function

I have read that I should add myScript before .nocache.js, But I can not do that in my case. Is there any other solution?

Upvotes: 1

Views: 433

Answers (2)

Mohamed Gamal
Mohamed Gamal

Reputation: 139

I solved the problem by replacing $wnd by $wnd.frames[0]. As the foo function is located inside this frame.

Upvotes: 1

Tobika
Tobika

Reputation: 1062

The error message says excactly what your problem is:
there is no function foo in the scope of $wnd.

$wnd refers to the parent of the iframe where your GWT code is running, so if you place your foo method inside the iframe it cant be found.
Try placing your foo method in your *.html file, where the .nocache.js is called.

Referring to your problem, that you add your javascript after the .nocache.js:
I had the same issue also and I fixed it with a timer, that waits until the Js is loaded.

private native boolean isLoaded()/*-{
    if (typeof $wnd.foo != 'undefined') {
        return true;
    }
    return false;
}-*/;

private void tryNotifyJs() {
    if (isLoaded()) {
        notifyJs();
    } else {
        Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {

            @Override
            public boolean execute() {
                tryNotifyJs();
                return false;
            }
        }, 100);
    }
}  

Upvotes: 0

Related Questions