emscripten-core / emscripten-core/emscripten
Async comunication with javascript
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
Here is a question on SO [How can I run an interactive program compiled with Emscripten in a web page?
](https://stackoverflow.com/q/48292269/387194)
And I came up with a hack that allows to send asynchronous messages from C to javascript and get the value from JS in C. So I can use it with the jQuery Terminal read method.
I've abused the fetch API and created a wrapper over XHR in JS that sends real XHR or my code if the URL is in a special format. The code can be found here
https://gist.github.com/jcubic/87f2b4c5ef567be43796e179ca08c0da
Does a better solution exist? Or will you consider adding this to emscripten to allow for Bidirectional async communication with javascript?
I was thinking about something like
```c
void read_async();
void success(void *text) {
printf("input: %s\n", text);
read_async();
}
void fail() {
printf("fail\n");
}
void read_async() {
char** args = {"name: "};
emscripten_async_js("read", args, &success, &fail);
}
int main() {
read_async();
}
```
and in JS the code can execute global read function and if returned promise resolve it will execute success in C with data like this:
```javascript
function read(prompt) {
display(prompt);
return new Promise(function(resolve, reject) {
if (true) {
resolve("hello");
} else {
reject();
});
}
```
and it will execute C function success with the string `"hello"`.
Contributor guide
Assessment
This issue has not been assessed yet.