WebAssembly can access the DOM through the Web API provided by the browser. This can be done by using the JavaScript functions window and document, which are available globally in the WebAssembly environment.
To interact with the DOM using WebAssembly, the code needs to be compiled with Emscripten or another WebAssembly compiler that provides bindings to the Web API. Once compiled, the WebAssembly code can call JavaScript functions that manipulate the DOM.
For example, the following code snippet demonstrates how to set the innerHTML of a div element from WebAssembly:
#include <emscripten.h>
#include <stdio.h>
EM_JS(void, setInnerHTML, (const char* elementId, const char* html), {
document.getElementById(elementId).innerHTML = html;
});
int main() {
setInnerHTML("myDiv", "Hello, world from WebAssembly!");
return 0;
}
In this example, the setInnerHTML
function is defined in JavaScript and is exposed to WebAssembly using the EM_JS
macro. The function takes an element ID and an HTML string as arguments and sets the innerHTML of the specified element to the given HTML string. The main
function in the WebAssembly code then calls the setInnerHTML
function to set the innerHTML of a div element with ID "myDiv".
Asked: 2023-05-12 04:34:32 +0000
Seen: 7 times
Last updated: May 12 '23