Skip to content

Using defineUnlistedScript for scripts injected into the main world overwrites a global variable #1738

@tstehr

Description

@tstehr

Describe the bug

We're using defineUnlistedScript to create a script that is subsequently inserted into websites via the content script, allowing it to interact with the main world, like done in the inject-script example.

We noticed that on particular websites having a script injected can lead to errors in page JavaScript. The problem happens even for empty scripts.

Investigating the error points to the output generated by defineUnlistedScript. In inject-script for example the generated file injected.js starts as follows:

var injected=function(){<...>}();

This leads to a property window.injected being set to undefined, since that is the return value of the function. This overwrite can interfere with a page script that also uses window.injected (or another variable that matches the name of an unlisted script being injected).

Reproduction

https://github.com/tstehr/repro-wxt-inject

Steps to reproduce

  1. Check out the test repo linked above
  2. run npm install and then npm run demo
  3. Run the inject-script example in a browser. I used pnpm dev:firefox.
  4. In that browser, visit the local server started in step 2.

Expected: The page displays "✅ The function has run"

Actual: The page continues to display "❌ The function has not yet run" and errors are shown in the developer console.

System Info

System:
    OS: macOS 15.5
    CPU: (10) arm64 Apple M2 Pro
    Memory: 80.66 MB / 32.00 GB
    Shell: 4.0.1 - /opt/homebrew/bin/fish
  Binaries:
    Node: 23.10.0 - ~/.nodenv/shims/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.9.2 - ~/.nodenv/shims/npm
    pnpm: 10.7.0 - /usr/local/bin/pnpm
  Browsers:
    Chrome: 137.0.7151.104
    Chrome Canary: 139.0.7236.0
    Firefox Nightly: 141.0a1
    Safari: 18.5
    Safari Technology Preview: 18.4
  npmPackages:
    wxt: ^0.20.5 => 0.20.5

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    pending-triageSomeone (usually a maintainer) needs to look into this to see if it's a bug

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions