Skip to content

webextension-polyfill incompatible with Manifest v3 #224

Closed as not planned
Closed as not planned

Description

@nnx0r

I believe that polyfill is injected by wxt at all times, even when manifest v3 is used for build?
Correct me if I am wrong, but polyfill should not exist for manifest v3.

Perhaps this is all that's needed:
mozilla/webextension-polyfill#329 (comment)

Aside, I'm having issues using browser.browserAction.setIcon() and browser.browserAction.setBadgeText() because on manifest v3, that's no longer correct API. It's now browser.action. If I have to create some of these fallbacks, then I think webextension-polyfill is useless for everything, except types. But then, we have chrome types here as an alternative: https://www.npmjs.com/package/@types/chrome

So perhaps you can make interface to match browser to be exact as chrome.

I'd love the option to opt-out of webextension-polyfill, so that I can create my own tiny wrapper, unless you see my point here, or unless I'm wrong and there's something that has to be enabled/disabled to make this work as expected?

Aside, how do I change manifest v2 to v3 for Firefox, because I want to test what may or may not work?

Activity

  1. added
    pending-triage
    on Nov 9, 2023
  2. nnx0r commented on Nov 9, 2023

    @nnx0r
    ContributorAuthor

    To answer some of these questions for myself and for the others, to create a different manifest build, just pass --mv3 to the build or dev commands.

    The --mv3 will not change service_worker to scripts for Firefox browser. So it can't work as expected.

    Still not sure how to get around all of it.

  3. aklinker1 commented on Nov 10, 2023

    @aklinker1
    Member

    Correct me if I am wrong, but polyfill should not exist for manifest v3.

    For the most part, you're correct. The polyfill is basically a noop for Chrome MV3 extensions, just like any other polyfill that is loaded into a environment where it's not needed.

    However, as a framework that supports more than just Chrome MV3 (Firefox MV2 and legacy Chrome MV2), WXT will not be dropping the polyfill until:

    1. Firefox releases MV3 support, which currently expiremental, and
    2. Google officially kills MV2

    Even after Firefox supports MV3, they've pledged to keep some of the MV2 APIs ad-blockers use, among other changes. This means that Chrome and Firefox will never be the same, and as developers, we will always have to do some form of feature detection.

    webextension-polyfill incompatible with Manifest v3

    This is just not true. It is 100% compatible with MV3. Including the polyfill does not break any of chrome's APIs. It just may not behave the way you expect it to.

    The polyfill provides a standardized, promise-based API that works on all browsers and all manifest versions, where possible. It cannot magically resolve breaking changes between manifest versions, like determining if it should call browser.pageAction or browser.browserAction for MV2 when calling browser.action. There will always be an edge case were it gets it wrong, so it's easier to make the developer implement feature detection.

    Note

    These APIs are mostly identical, so you can use use await (browser.action ?? browser.pageAction).setIcon(...) as a quick work around for one-off function calls. If the API is not available for both manifest versions, typescript will report a type error.

    Since WXT needs to support all browsers and all manifest versions, including combinations you may not be using, WXT will continue to use webextension-polyfill internally, and it will continue to add the polyfill to content scripts and any other entrypoints where you use wxt/browser.

    But like I said in another post, you don't have to use the browser variable WXT provides. You can use chrome and install the types you mentioned. If you're concerned about the additional size that webextension-polyfill takes up in the production bundle (40 kb per entrypoint), you can tell Vite to resolve it to a custom module you provide.

    Warning

    This is a hack and I make no promises to support it.

    // wxt.config.ts
    import { defineConfig } from 'wxt';
    import path from 'node:path';
    
    export default defineConfig({
      vite: () => ({
        resolve: {
          alias: {
            '^webextension-polyfill$': path.resolve("chrome.js")
          },
        },
      }),
    });
    // chrome.js
    export default chrome
  4. added
    wontfix
    invalid
    and removed
    pending-triage
    on Nov 10, 2023
  5. aklinker1 commented on Nov 10, 2023

    @aklinker1
    Member

    The --mv3 will not change service_worker to scripts for Firefox browser. So it can't work as expected.

    I don't understand the issue here. wxt build -b firefox --mv3 should use service_worker for the background since it's MV3.

    wxt build -b firefox and wxt build -b firefox --mv2 will use scripts for the background.

    I'm 99% sure I have E2E tests that cover this behavior, and I know it works like this for several of my own extensions that target Firefox MV2.

  6. nnx0r commented on Nov 10, 2023

    @nnx0r
    ContributorAuthor

    Thank you for your input!
    I'll check this out today and see where it leads me.

    Polyfill is compatible between browers, but what you said... Doesn't cover differences between MV2 and MV3. Which for my case, I think, would be only what I mentioned in this issue.


    It's not abound 40kb additional size per entry, but more of why would I ship it, if it isn't needed.

    I'll try that Vite approach you gave me, and see how it goes. For my case, MV3 will work for Firefox too, with the exception of service_worker not being supported.

    What I meant by --mv3 flag not working when passing it to build option as -b firefox --mv3 is that it doesn't care that the target is Firefox and keeps using background.service_worker instead of background.scripts[].

    I understand that most extensions will benefit from WXT having webextension-polyfill as batteries included, but I wonder why wouldn't you consider making it possible to opt-out by configuration?

  7. aklinker1 commented on Nov 10, 2023

    @aklinker1
    Member

    What I meant by --mv3 flag not working when passing it to build option as -b firefox --mv3 is that it doesn't care that the target is Firefox and keeps using background.service_worker instead of background.scripts[].

    I was still confused by this, because my understanding was that Firefox requires backgroumd.service_worker for MV3, just like chrome and Safari.

    But after reading Mozilla's docs again, that doesn't seem to be true...

    It appears Firefox requires you to use scripts or page for MV3, making sure to set persistent: false... Is that true?

    I haven't actually tried running a MV3 extension on Firefox before, I'll give it a go today and fix this if true.

    I understand that most extensions will benefit from WXT having webextension-polyfill as batteries included, but I wonder why wouldn't you consider making it possible to opt-out by configuration?

    Because the polyfill is essential for the internal logic in dev mode and it is essential for the internal logic for managing the lifecycle of content scripts in production. I'm not 100% convinced that removing it will not break anything.

    If the hack works for you, let me know. I will consider adding an experimental.webextensionPolyfill option that applies this patch when set to false. But even when set to false, it would still be included in dev mode or if the target is Firefox or if the target is MV2 (times when the polyfill is required). I also need to consider how Safari will best work, Safari is weird and different.

    Edit: Actually no, I'm not going to add an experimental setting. WXT is an opinionated framework built around the polyfill, until it's not needed, I'm not going to add an option to remove it.

    Edit 2: But in preparation for that day, an experimental config option would be useful... In that case setting the flag to false should disable the polyfill completely, even in dev mode and even for MV2. Ok, that makes sense. I'll do that lol. I'm done arguing with myself.

  8. nnx0r commented on Nov 10, 2023

    @nnx0r
    ContributorAuthor

    Hahah I had a great laugh reading your comment with multiple edits... 🤣
    I tried the Vite setting you gave me, but apparently it did nothing regarding exclusion of polyfill or I failed to do it properly.

    Regarding Firefox, I tried my base of extension built with --mv3 and it shows up error.

    { service_worker: 'background.js' } must be replaced with { scripts: ['background.js'] } and persistant flag must not exist. Scroll to Event-driven background scripts section


    Happy to hear that you will implement an experimental feature flag. Aside, I tried making a sample with Vite (without WXT) to see if I will have everything cross-browser compatible without polyfill and I have no issues at all.

    Here's my attempt, so it may help with the feature flag thingy... That is, if you want to extend it with these additions.

    package.json

    {
      "devDependencies": {
        "chrome-types": "^0.1.241",
      }
    }

    src/shims.d.ts

    export {}
    
    declare global {
      declare var browser: typeof chrome
    }

    src/background.ts (for example)

    if (!('browser' in globalThis)) {
      browser = chrome
    }
    
    ;(async () => {
      // Because I have hard times enabling top-level await
      console.log(browser)
    })()

    Judging by WXT's implementation of how webextension-polyfill is automatically injected in each input that uses it, I assume there's a magic trick with Vite, I'm not aware of that could be used to add that condition on top of every input? Feel free to reveal your magic to me, I'd be happy to learn.

    EDIT:
    Of course my little background code won't work if I have any imports. Not sure how to properly handle it.

  9. aklinker1 commented on Nov 10, 2023

    @aklinker1
    Member

    https://extensionworkshop.com/documentation/develop/manifest-v3-migration-guide/

    Ok, wow, firefox's MV3 support is already out? I did not know that... It also looks like Firefox 105 and above will be compatible for the most part, and Firefox 109 and above will be 100% compatible. Both have been out for a while, long enough that most users are above those versions.

    Ok, so now I understand more context around this issue. For now, I'm gonna stick with an experimental flag. I need to spend some time making sure Safari is compatible as well.

  10. aklinker1 commented on Nov 10, 2023

    @aklinker1
    Member

    Feel free to reveal your magic to me, I'd be happy to learn.

    The magic comes from 2 things: unimport and Vite's virtual modules.

    Unimport

    unimport is configured so that anytime you use the browser variable, it imports wxt/browser:

    { package: 'wxt/browser' },

    Which simply imports the polyfill.

    import originalBrowser, { Browser, Runtime, I18n } from 'webextension-polyfill';

    At build time, unimport does not know that browser may already exist at runtime, so it adds the import at the top of all your files during the build process.

    Virtual Modules

    Instead passing your entrypoints/*.ts files into Vite to build, WXT uses it's own "virtual entrypoints" when bundling the TS file.

    const isVirtual = [
    'background',
    'content-script',
    'unlisted-script',
    ].includes(entrypoint.type);
    const entry = isVirtual
    ? `virtual:wxt-${entrypoint.type}?${entrypoint.inputPath}`
    : entrypoint.inputPath;

    So here, if the entrypoint needs to be virtualized, like a content script, instead of building /path/to/entrypoints/content.ts, it tells Vite to build virtual:wxt-content-script?/path/to/entrypoints/content.ts. There's nothing special about this string yet. By default, Vite would look for a node module with that name, notice it doesn't exist, and throw a build error. We need to tell Vite that when it sees this string, it should use WXT's entrypoint. We do that in a Vite plugin:

    const virtualId = `virtual:wxt-${type}?`;
    const resolvedVirtualId = `\0${virtualId}`;
    return {
    name: `wxt:virtual-entrypoint`,
    resolveId(id) {
    // Id doesn't start with prefix, it looks like this:
    // /path/to/project/virtual:background?/path/to/project/entrypoints/background.ts
    const index = id.indexOf(virtualId);
    if (index === -1) return;
    const inputPath = normalizePath(id.substring(index + virtualId.length));
    return resolvedVirtualId + inputPath;
    },
    async load(id) {
    if (!id.startsWith(resolvedVirtualId)) return;
    const inputPath = id.replace(resolvedVirtualId, '');
    const template = await fs.readFile(
    resolve(
    config.root,
    `node_modules/wxt/dist/virtual/${type}-entrypoint.js`,
    ),
    'utf-8',
    );
    return template.replace(`virtual:user-${type}`, inputPath);
    },
    };

    This plugin basically says: When you see a virtual entrypoint, use one of these files:

    The content script virtual entrypoint is a good example of this:

    import definition from 'virtual:user-content-script';
    import { logger } from '~/client/utils/logger';
    import { ContentScriptContext } from '~/client/content-scripts/content-script-context';
    (async () => {
    try {
    const { main, ...options } = definition;
    const ctx = new ContentScriptContext(__ENTRYPOINT__, options);
    await main(ctx);
    } catch (err) {
    logger.error(
    `The content script "${__ENTRYPOINT__}" crashed on startup!`,
    err,
    );
    }
    })();

    It does several things:

    1. Import another virtual module, virtual:user-content-script, on line 1
    2. Creates the content script context variable
    3. Calls the main function from the content script definition.

    virtual:user-content-script is another virtual entrypoint, but instead of using a custom resolveId function like we did before, the plugin from above just does a find/replace to tell it to import your file instead.

    return template.replace(`virtual:user-${type}`, inputPath);

  11. nnx0r commented on Nov 10, 2023

    @nnx0r
    ContributorAuthor

    Hot damn, this is amazing. Thank you for your time and effort trying to explain all this to me. Much appreciated!

  12. nnx0r commented on Nov 13, 2023

    @nnx0r
    ContributorAuthor

    I'm unsure if I am doing something wrong here.

    • experimental feature set in the config
    // wxt.config.ts
    experimental: {
      includeBrowserPolyfill: false,
    }
    
    • alias added
    // wxt.config.ts
    vite: () => ({
      resolve: {
        alias: {
          'webextension-polyfill': 'polyfill.js',
        },
      },
    }
    • polyfill.js created
    export default chrome
    

    Also tried this, as I used it elsewhere and doesn't work:

    if (!('browser' in globalThis)) {
      globalThis.browser = chrome
    }
    
    const browser = globalThis.browser
    export default browser
    
    Screenshot 2023-11-13 at 19 52 50
  13. nnx0r commented on Nov 13, 2023

    @nnx0r
    ContributorAuthor

    Okay, figured it out. So these two things are for two different purposes.

    1. Using alias in Vite's config, will use my custom polyfill wherever webextension-polyfill was meant to be used.

    2. Using experimental feature flag, will omit the webextension-polyfill entirely from the output.

    Both can't be used at the same time and shouldn't be used. It's either one or the other, correct?

    Since I'm building cross-browser extension, my tiny polyfill for MV3 only support - makes sense to me. Please fill me up if I am wrong.

  14. aklinker1 commented on Nov 14, 2023

    @aklinker1
    Member

    Yup, you don't need to do anything except for setting the experimental flag. WXT will setup the alias behind the scenes for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    invalidwontfix

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions