xpenatan / gdx-teavm

Run Libgdx in a webbrowser with teavm
Apache License 2.0
107 stars 16 forks source link

how to use js library? #113

Closed thawri1 closed 8 months ago

thawri1 commented 8 months ago

I want to use js library in my game. for example Yandex Game SDK: https://yandex.com/dev/games/doc/en/sdk/sdk-about is it possible?

thawri1 commented 8 months ago

I found this: https://teavm.org/docs/runtime/jso.html but stuck at the import module section

this code works:

    @JSBody(
        params = { "message" },
        script = "console.log(message)"
    )
    public static native int callModule(String message);

but if I add import, not working:

@JSBody(
        script = "return testModule.foo();",
        imports = @JSBodyImport(
            alias = "testModule",
            fromModule = "testModule.js"))
    public static native int callModule();

js console showing this error: Uncaught TypeError: Cannot read properties of undefined (reading 'foo') maybe the testModule.js file location is wrong. I tested in the root folder, assets folder, and beside the TeaVmLauncher class. I have also tested the full path address.

thawri1 commented 8 months ago
private static final String addYandexLibScript = "var my_awesome_script = document.createElement('script');\n" +
        "\n" +
        "my_awesome_script.setAttribute('src','https://yandex.ru/games/sdk/v2');\n" +
        "\n" +
        "document.head.appendChild(my_awesome_script);";

    @JSBody(script = addYandexLibScript)
    public static native void addYandexLib();

    private static final String yandex =  "YaGames\n" +
        "    .init()\n" +
        "    .then(ysdk => {\n" +
        "        console.log('Yandex SDK initialized');\n" +
        "        window.ysdk = ysdk;\n" +
        "    });";

    @JSBody(script = yandex)
    public static native void initYandex();