Anil8753
Anil8753

Reputation: 2731

How to call javascript method from C++ with parameters using EM_JS

I just gone through Calling JavaScript from C/C++ and followed their instructions. I am able to call the Js method from C++

C++

#include <iostream>
#include <string>

#include <emscripten.h>
#include <emscripten/bind.h>

EM_JS(void, call_js, (), {
    jsMethod();
});

bool callJsBack()
{
    call_js();
    return true;
}

EMSCRIPTEN_BINDINGS(module)
{
    emscripten::function("callJsBack", &callJsBack);
}

Js

<script>
    var Module = {
        onRuntimeInitialized: function() {
            console.log('Module.callJsBack(): ' + Module.callJsBack());
        }
    };

    function jsMethod() {
        alert('I am a js method!');
    }
 </script>

I want to make the jsMethod() parameterized (want to pass the string from the C++ at the time of calling jsMethod()).

function jsMethod(msg) {
    alert(msg);
}

I did not find any example or suggestion to achieve this requirement.

Upvotes: 4

Views: 3967

Answers (1)

Anil8753
Anil8753

Reputation: 2731

Found the answer:

C++

EM_JS(void, call_js_agrs, (const char *title, int lentitle, const char *msg, int lenmsg), {
    jsMethodAgrs(UTF8ToString(title, lentitle), UTF8ToString(msg, lenmsg));
});

bool callJsBackWithAgrs()
{
    const std::string title = "Hello from C++";
    const std::string msg = "This string is passed as a paramter from C++ code!";
    call_js_agrs(title.c_str(), title.length(), msg.c_str(), msg.length());
    return true;
}

EMSCRIPTEN_BINDINGS(module)
{
    emscripten::function("callJsBackWithAgrs", &callJsBackWithAgrs);
}

Js:

var Module = {
    onRuntimeInitialized: function() {
        Module.callJsBackWithAgrs();
    }
};

function jsMethodAgrs(title, msg) {
    alert(title + '\n' + msg);
}

complete working example: CallJsFromCpp

Upvotes: 5

Related Questions