ruby-wasm
ruby-wasm copied to clipboard
DOM interaction
I just tried this out and am fairly impressed! Just wondering, is it possible yet to interact with the DOM from my ruby script?
Okay, so I managed to at least execute JS code from ruby (without getting any return value though).
I extended assets/mruby_init.c to provide a global ruby method run_js that uses the emscripten API to run JS code in the browser:
#include <mruby.h>
#include <mruby/irep.h>
#include <emscripten.h>
mrb_value run_js(mrb_state* mrb, mrb_value self)
{
char *js_code;
mrb_get_args(mrb, "z", &js_code);
emscripten_run_script(js_code);
return self;
}
int main() {
mrb_state *mrb = mrb_open();
if (!mrb) { /* handle error */ }
mrb_define_method(mrb, mrb->kernel_module, "run_js", run_js, MRB_ARGS_REQ(1));
mrb_load_irep(mrb, ruby_app);
// If an exception, print error
if (mrb->exc) mrb_print_error(mrb);
mrb_close(mrb);
return 0;
}
When compiling the following hello.rb to wasm, the browser shows the alert.
run_js("window.alert(\"foo\");")
I don't know whether this is a good approach or if it was even possible in another, more straightforward way. But if not, this proof of concept could be encapsulated into a mrbgem that defines some API to interact really in both directions with the DOM in the browser.
Could this be possible using this crate?
https://github.com/web-dom/web-dom