Reference · Browser

js

signature
js(str, any...) -> any

What it does

Calls a function of the page's own scripts, found from the page's globals by its dotted name (js("L.map", el), js("navigator.clipboard.writeText", text)), and gives its result. With no arguments and a name that is not a function, it reads the value (js("window.innerWidth")). It runs in the browser, from a component; while the server renders the component it gives null. A name the page does not have is an error value, not a runtime error.

A library named on a client line is called the same way, as JavaScript reads it: client /assets/leaflet.js use L, then L.map(el) is js("L.map", el) and L.version reads a value, and the page loads the script itself (see JavaScript libraries).

Examples

in a program
component Theme() {    state dark = js("localStorage.getItem", "theme") == "dark"    <button @click={() => {        dark = !dark        js("localStorage.setItem", "theme", dark ? "dark" : "light")        js("document.body.classList.toggle", "dark", dark)    }}>{dark ? "Light" : "Dark"}</button>}component Share(link: str) {    state copied = false    <button @click={() => {        let r = js("navigator.clipboard.writeText", link)        copied = !is_err(r)    }}>{copied ? "Copied" : "Copy link"}</button>}

Edge cases

print(js("window.innerWidth"), js("Chart.register", 1))print(js("localStorage.getItem", "theme") ?? "light")
output
null nulllight

Errors

A first argument that is not a string is a runtime error on the server. In the browser, giving arguments to a name that is not a function (js("document.title", "x")) is a runtime error too (`js`: document.title is not a function), written to the console; a missing name is an error value, as above.

this one fails
print(js(42))
output
line 1: `js` takes the name of what it calls first: js("Chart", ...)

Chaining

js takes the name first, so it is rarely the target of a pipeline; its result is:

in a program
let width = js("window.innerWidth") ?? 0let rows = js("JSON.parse", text) | filter((r) => r.ok)

See also

js_new, ask, notify, http.get

Thread
12Useful? Like it, or add to its thread below.

Thread 0 posts

On js(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo