JSInterop native class

Skip to first unread message

George Paret

Feb 24, 2023, 4:41:17 PM2/24/23
to GWT Users
I am attempting to use a javascript class in GWT. Here is the sample code I am using.

Javascript file - rhombus.js

class Rhombus {
    static isReady() {
        return true;

Java file - Rhombus.java

package com.xyz.graphics;

import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

@JsType(isNative = true, namespace = JsPackage.GLOBAL)
public class Rhombus {
    public static native boolean isReady();

<script src="js/rhombus.js"></script>
<script src="app/app.nocache.js"></script>

When I try to access Rhombus.isReady(), I get
(TypeError) : Cannot read properties of undefined (reading 'isReady')

However I can access the method correctly if I attach Rhombus to the window object.

<script type="text/javascript">
    window.Rhombus = Rhombus;

I don't understand why attaching the class to the window object is necessary, as none of the documentation makes a mention of that.

Thomas Broyer

Feb 24, 2023, 5:37:47 PM2/24/23
to GWT Users
Because GWT code runs in an iframe, JsPackage.GLOBAL maps to the JSNI $wnd equivalent referencing the parent window so anything referenced from JsInterop needs to be recorded as a window property; and classes aren't recorded on the window per ECMAScript (see https://stackoverflow.com/a/37711826/116472), this is why you need to do it explicitly to expose them to JsInterop.

George Paret

Feb 24, 2023, 10:45:08 PM2/24/23
to GWT Users

Thank you for the detailed reply. I would have never figured out by myself that functions are recorded on the window but classes are not.

Although this is probably the first time I posted a question here, I have immensely benefited from your helpful responses here, stackoverflow and various other forums. Your volunteer efforts are greatly appreciated.

Reply all
Reply to author
0 new messages