5

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.

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.