Skip to content

injectScript passing data to the script #1755

@ion1

Description

@ion1

Feature Request

It would be nice if something like this was possible:

await injectScript("/script.js", {
  parameter: [1, 2, 3],
});
// entrypoints/script.ts
export default defineUnlistedScript({
  main<number[]>(ctx) {
    console.info(ctx.parameter); // [1, 2, 3]
  },
);

where injectScript would do something like this:

if (parameter !== undefined)
  script.dataset["wxtParameter"] = JSON.stringify(parameter);

and the build result from entrypoints/script.ts would include something like this:

const parameterString = document.currentScript?.dataset?.["wxtParameter"];
const parameter = parameterString !== undefined ? JSON.parse(parameterString) : undefined;
return await defintion.main({ parameter });

Additionally, if #1754 is implemented, this could type-check the parameter against the type of the function.

// entrypoints/content.ts
import script from "./script";

export default defineContentScript({
  matches: ["https://example.net/*"],
  async main() {
    await injectScript(script, {
      parameter: [1, 2, 3], // type-checked
    });
  },
});

Thanks!

Is your feature request related to a bug?

N/A

What are the alternatives?

Leaving things as they are.

Additional context

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions