wasm-bindgen: Generated bindings with no-modules target causes error in web extensions

Describe the Bug

I am trying to build a web extension using Mubelotix/wasm-extension-template as a template, but I get a javascript error inside the generated bindings when loading the generated extension in a browser: Uncaught TypeError: Cannot read properties of null (reading 'src')

The linked template uses wasm-pack with the cli argument --target=no-modules which generates binding code that starts like so:

let wasm_bindgen;
(function() {
    const __exports = {};
    let script_src;
    if (typeof document === 'undefined') {
        script_src = location.href;
    } else {
        script_src = new URL(document.currentScript.src, location.href).toString();
    }
    let wasm;
    // ...

In the context of a web extension, document is defined but document.currentScript is null. This causes a TypeError when document.currentScript.src is executed.

The current main branch (commit 153a6aa9c7a989c1865df7f93b2ddbca1113a175) seems to output different code, as seen here:

if (typeof document !== 'undefined') {
    script_src = new URL(document.currentScript.src, location.href).toString();
}

I haven’t managed to build the main branch of wasm-pack yet to try this out, but I assume it will produce the same error.

Steps to Reproduce

  1. Clone Mubelotix/wasm-extension-template
  2. Build the extension with sh build.sh
  3. Inside a chromium-based browser, load the extension as an unpacked extension by following Chrome’s documentation.
  4. Browse to https://example.com, open devtools and observe the error.

Expected Behavior

Wasm-bindgen should account for cases where document.currentScript is null or undefined and have a fallback.

Actual Behavior

Wasm-bindgen assumes document.currentScript is not null when document is not undefined.

Additional Context

  • wasm-pack version: 0.11.0
  • wasm-bindgen version: 0.2.83 (shipped with wasm-pack, I presume)

I am testing on Windows using the Brave browser.

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 2
  • Comments: 16 (2 by maintainers)

Commits related to this issue

Most upvoted comments

It’s the wasm-bindgen-cli binary. So cargo install wasm-bindgen-cli --git https://github.com/daxpedda/wasm-bindgen --branch fix-3402 (you might need --force) should probably do it.

If there is an error about non-matching versions, use the following in your Cargo.toml:

[patch.crates-io]
js-sys = { git = "https://github.com/daxpedda/wasm-bindgen", branch = "fix-3402" }
wasm-bindgen = { git = "https://github.com/daxpedda/wasm-bindgen", branch = "fix-3402" }
wasm-bindgen-futures = { git = "https://github.com/daxpedda/wasm-bindgen", branch = "fix-3402" }
wasm-bindgen-test = { git = "https://github.com/daxpedda/wasm-bindgen", branch = "fix-3402" }
web-sys = { git = "https://github.com/daxpedda/wasm-bindgen", branch = "fix-3402" }