Skip to content

Providing a unique ID for secure communication between MAIN and ISOLATED worlds #1756

@ion1

Description

@ion1

Feature Request

I have been thinking about ways to implement communication between MAIN and ISOLATED worlds that the website cannot detect or interfere with.

My current approach is for an ISOLATED content script to run at document_start, check that the DOM is empty (so the page presumably has had no opportunity to monkey-patch the API), inject a MAIN script which makes copies of pristine API methods, and pass a unique ID to the script for communication through custom window events using the ID.

I can use new URL(browser.runtime.getURL("/script.ts")).hostname to get a unique ID – either the static extension ID (which the page could predict with knowledge about the extension) or the dynamic ID (which it couldn't) depending on what I use as the use_dynamic_url value for the script.

Since I am probably not the only user who would benefit from such an ID, it might be nice if WXT had something like this:

const { id } = await injectScript("/script.js");
console.info(id); // "a8c42380-8b9c-4429-8209-15de68a34657"
// entrypoints/script.ts
export default defineUnlistedScript({
  main({ id }) {
    console.info(id); // "a8c42380-8b9c-4429-8209-15de68a34657"
  },
});

where injectScript gets the hostname out of the URL and passes it to the script using something like this:

script.dataset["wxt-id"] = id;

and the build result of entrypoints/script.ts does something like this:

const id = document.currentScript?.dataset?.["wxt-id"];
return await definition.main({ id });

An alternative would be to decouple the type of the ID from the use_dynamic_url value for a specific script, and instead add something like the following to the manifest and to provide a getDynamicId based on it that could be passed to an injected script as a parameter using #1755.

{
  web_accessible_resources: [
    // Added by WXT
    {
      resources: [".wxt-dynamic-id-provider.txt"],
      use_dynamic_url: true,
    },
  ],
}
// Provided by WXT
export function getDynamicId(): string {
  return new URL(browser.runtime.getURL("/.wxt-dynamic-id-provider.txt")).hostname;
}
// Independent of the use_dynamic_url value used for script.js.
await injectScript("/script.js", {
  parameter: getDynamicId(),
});

Is your feature request related to a bug?

N/A

What are the alternatives?

Having the users run new URL(browser.runtime.getURL("/script.ts")).hostname and pass that to the injected script by themselves.

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