Chapter 18: DOM, Storage, Workers, and JavaScript Interop
⚠ Partly planned. The first section, on
web.dom,web.storageandweb.js, runs today in the browser runtime (Chapter 1, "Running Loup in the browser"). The rest describes the design in the Language Reference (§2-3.1–§2-3.3 for JavaScript interop, §2-1.10 for workers, §1-16.6.5 for passing data to scripts). The toolchain does not implement that design yet, so those listings are design sketches and are not verified, apart from the compiler checks shown with real output.
Sometimes a browser app has to reach past the reactive UI of Chapter 16: call JavaScript, touch the DOM, store data, or move work off the main thread. This chapter starts with the modules the browser runtime provides, then covers what the Reference specifies and says where it specifies nothing.
What runs today: web.dom, web.storage and web.js
These three modules are in the standard library. Their functions act on the page, so they work in the browser runtime, not under loup run on the host.
web.dom reaches the page:
| Name | Does |
|---|---|
getElementById(id), querySelector(selector) |
Find an element in the document; Option[Element]. |
createElement(tag) |
Create a detached element. |
Element methods |
text() / setText, html() / setHtml, value() / setValue, getAttribute (an Option[string]), setAttribute, removeAttribute, querySelector, appendChild, remove, and on(event, handler) (also spelled addEventListener). |
Event methods |
eventType(), target(), preventDefault(), stopPropagation(). |
setTimeout(ms, handler), clearTimeout(id) |
Run a closure later on the browser's event loop. |
fetch(url, onDone), fetchRequest(url, method, body, onDone) |
Make an HTTP request and pass the Response (status(), ok(), text()) to a callback. |
web.storage has localStorage() and sessionStorage(), each a Storage with get(key) (an Option[string]), set, remove and clear. Listing 1-3 keeps a counter in it.
web.js crosses into JavaScript with one string each way. callJs(name, arg) calls a function the page registered with loup.registerJsFunction(name, fn) (or passed as jsFunctions to LoupRuntime.load), or else a global function of that name. exportFn(name, handler) makes a Loup closure callable from JavaScript as loup.exports[name](arg). Pass anything structured as JSON text.
@mode(web.scripted)
from web.dom import (getElementById, setTimeout, fetch, Response);
from web.js import (callJs, exportFn);
let status = getElementById("status").unwrap();
println("Title from JavaScript: " + callJs("pageTitle", ""));
exportFn("shout", func(text: string): string {
return "Loup heard: " + text;
});
setTimeout(100, func(): void {
status.setText("The timer fired.");
});
fetch("data.json", func(res: Response): void {
println("GET data.json -> " + res.status().to_string() + " " + res.text().trim());
});
Listing 18-1: The DOM, a timer, fetch and JavaScript interop (runs in the browser)
The page registers the function before it runs its scripts, and keeps the runtime so other JavaScript can call the export:
loup.registerJsFunction("pageTitle", () => document.title);
await loup.runPageScripts();
console.log(loup.exports.shout("hello")); // Loup heard: hello
On a page titled Loup example 4 with <p id="status"> and a data.json holding {"greeting": "hi"}, the output is:
Title from JavaScript: Loup example 4
GET data.json -> 200 {"greeting": "hi"}
After 100 ms the paragraph reads The timer fired.. The fetch callback runs when the response arrives, after the script's last statement; it does not return a Task, because the runtime has no task scheduler yet (Chapter 15).
These modules are the runtime's own first version. The Reference's typed interop, extern js and @jsexport, and its lang.interop.js facades are what the next sections describe.
Calling JavaScript: extern js
An extern js declaration gives a JavaScript function or value a Loup type (§2-3.1):
@mode(web.compiled)
extern js func parseInt(s: string, radix: int): int;
extern js func fetchJson(url: string): Task[string];
extern js val document: Any;
Listing 18-2: JavaScript declarations (design sketch)
The declared types are trusted, not checked, so a mismatch is a runtime FfiTypeError. A function returning a Promise is declared with a Task[T] result. A typed array backed by a SharedArrayBuffer needs @unsafe("sharedMemory: …") on the declaration. extern js needs a JavaScript host (browser, node, bun, deno), and the toolchain already rejects it in a native program:
@mode(host.native)
extern js func parseInt(s: string, radix: int): int;
func main(): void {
println("never runs");
}
main.lphc:3:1: error[E0001]: E_EXTERN_JS_NOT_NATIVE: 'extern js' is not available in 'host.native' or 'freestanding' modes; use 'web.scripted', 'web.compiled', 'host.scripted', or 'host.dual'
A native binary has no JavaScript engine, so keep bindings in a web file. There the declaration is accepted today, but calling it fails to type-check (type of 'parseInt' is not yet known), because nothing binds it.
Being called from JavaScript: @jsexport
@jsexport makes a module-level func or async func a named export of the compiled module (§2-3.2). Arguments are converted to the declared Loup types (FfiTypeError on failure), an async export returns a Promise, and the annotation is valid only for the browser and service targets. A synchronous export must not await (E_JSEXPORT_AWAIT), and the toolchain checks that already:
@mode(web.compiled)
async func fetchSummary(userId: string): Task[string] {
return "summary for " + userId;
}
@jsexport
func onMessage(userId: string): void {
let summary = await fetchSummary(userId);
println(summary);
}
func main(): void {
onMessage("ann");
}
main.lpweb:7:1: error[E0001]: Synchronous @jsexport function must not contain 'await'
JavaScript calls a synchronous export synchronously, so it cannot wait. Make the export async so JavaScript receives a Promise; main becomes async too, which ruling MAIN-1 allows:
@mode(web.compiled)
async func fetchSummary(userId: string): Task[string] {
return "summary for " + userId;
}
@jsexport
async func onMessage(userId: string): Task[void] {
let summary = await fetchSummary(userId);
println(summary);
}
async func main(): Task[void] {
await onMessage("ann");
}
Listing 18-3: An asynchronous @jsexport function
summary for ann
On the interpreter onMessage is an ordinary function; nothing is exported yet.
Typed facades: lang.interop.js
For common browser APIs the Reference specifies typed wrappers in lang.interop.js and recommends them over raw extern js (§2-3.3): fetch returning Task[Response]; setTimeout, setInterval and their clear functions; and, on the browser target, querySelector(selector): Option[Element], querySelectorAll, and Element and Event classes.
@mode(web.compiled)
from lang.interop.js import (querySelector, Event);
func wireDismissButton(): void {
match querySelector("#dismiss") {
Some(button) => {
button.addEventListener("click", func(e: Event): void {
e.preventDefault();
button.remove();
});
},
None => printErr("no #dismiss button on this page"),
}
}
Listing 18-4: DOM access through the typed facade (design sketch)
A missing element is a None you must handle, not a null that fails later.
web.dom, web.storage and workers
The Reference mentions web.dom and web.storage (ShadowRoot lives in web.dom) but does not specify them; their only specification is the stdlib requirement documents. What the browser runtime implements is the first section of this chapter. There is no history (pushState) or cookie API yet.
For parallel work the Reference specifies ScriptWorker[M] in concurrent: an isolated Wasm instance with its own heap that exchanges Sendable messages with the page (§2-1.10.2). The worker module exports a workerMain function:
@mode(web.compiled)
from concurrent import (WorkerChannel);
pub async func workerMain(channel: WorkerChannel[bytes]): Task[void] {
while (true) {
let msg = await channel.receive();
if (msg.is_none()) {
break;
}
channel.reply(checksum(msg.unwrap()));
}
}
Listing 18-5: A worker module, src/hasher.lpweb (design sketch; checksum is assumed)
The page starts it with await ScriptWorker[bytes].spawn("./hasher.lpweb"), then uses send, await receive() and terminate(). Messages are copied, never shared, and a worker has no ui, web.dom, web.storage or extern js (§2-1.10.5). The web.workers API of earlier drafts (postMessage, onMessage) is not in the Reference. Today there is no concurrent module; the prelude's spawnWorker(path) runs workerMain to completion at the first receive() or join() and starts no browser worker (Chapter 15).
Passing data to JavaScript
Never interpolate into an inline <script> or <style> block: the Reference makes any {$ … $} there E_SCRIPT_STYLE_INTERPOLATION (§1-16.6.5), because JavaScript and CSS cannot be escaped with a substitution table. Use a data- attribute, or the SSR state block (Chapter 19):
@mode(web.compiled)
func appRoot(userName: string): string {
let root = ```(html):(none)
<div id="app" data-user="{$ userName | escape $}"></div>
```;
return root.render({});
}
func main(): void {
println(appRoot("ann"));
println(appRoot("\"><img src=x onerror=alert(1)>"));
}
Listing 18-6: Handing a value to the page through a data- attribute
<div id="app" data-user="ann"></div>
<div id="app" data-user=""><img src=x onerror=alert(1)>"></div>
This listing runs today because it only renders a fence to a string. The <script> check is not implemented yet, and html fences do not escape attribute values yet (Chapter 14), so the listing escapes the value itself with the escape filter; the second call shows a hostile value staying inside the attribute.
Summary
- In the browser runtime,
web.domgives elements, events, timers andfetch,web.storagegiveslocalStorage/sessionStorage, andweb.jscalls JavaScript and exports Loup closures with string arguments. - Typed JavaScript interop, the
lang.interop.jsfacades and workers are planned (Language Reference §2-3, §2-1.10). extern jsdeclares typed JavaScript bindings; the toolchain already reportsE_EXTERN_JS_NOT_NATIVEin native code.@jsexportexports Loup functions; the toolchain already rejectsawaitin a synchronous export.lang.interop.jsis the specified facade forfetch, timers and the DOM;web.domandweb.storageare reserved but unspecified.- Workers are
ScriptWorker[M]with aworkerMain(channel)entry; today only a batch-modespawnWorkerexists. - Pass data to scripts through
data-attributes or the SSR state block, never by interpolating into<script>.