Code Monkey home page Code Monkey logo

chrome-extension-tools's Introduction

CRXJS

What is CRXJS?

CRXJS is a project to bring a modern developer experience to the Chrome Extension ecosystem. This repo houses two bundling libraries: a modern Vite plugin and a legacy Rollup plugin.

Get Started in 90 seconds.

Features

If you're starting a new Chrome Extension project, consider using @crxjs/vite-plugin. This Vite plugin brings all the features of Vite to the Chrome Extension developer experience.

@crxjs/vite-plugin rollup-plugin-chrome-extension
Works on Vite Rollup
Simple Config Yes Yes
HMR True HMR Auto-reload
Static Asset Imports Yes With config
MV3 Yes Yes
MV2 - Yes
Auto Web-accessible Resources Yes -
Documentation CRXJS Vite Plugin Docs Extend Chrome Docs
NPM npm (scoped) npm (scoped)

Supporting

If these plugins have helped you ship your product faster, please consider sponsoring me on GitHub.

Contributing

We encourage pull requests! This is a pnpm monorepo, so use pnpm instead of Yarn or npm.

chrome-extension-tools's People

Contributors

a-shleifman avatar ale-ben avatar amysteam avatar anatolykopyl avatar andarist avatar citrusfruits avatar detachhead avatar elwin013 avatar floer32 avatar fractalo avatar github-actions[bot] avatar hovavo avatar ibz786 avatar jacksteamdev avatar jaiakash avatar jones-sam avatar jpozo20 avatar leave-it-blank avatar lioness100 avatar marcoreni avatar mnoorenberghe avatar mubaidr avatar plusminushalf avatar rbhalla avatar remixz avatar renovate-bot avatar renovate[bot] avatar ryoid avatar xianjianlf2 avatar yinjs avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chrome-extension-tools's Issues

Manifest v3 support

Is your feature request related to a problem? Please describe.

I tried to use your plugin but when I build my project with manifest v3 then an error message says that the maximum manifest version is only v2 :(

Describe the solution you'd like

Allow a manifest.json which contains a more secure and performance optimized browser API:

    "manifest_version": 3,

Describe alternatives you've considered

Stop using your plugin and wait for an update.

Additional context

Validation errors are hard to read

Describe the bug
As is, the validation errors we emit are not very easy to read.

To Reproduce
Steps to reproduce the behavior:

  1. Attempt to bundle a Chrome extension with an invalid manifest.
  2. Try to decipher the JSON output logged to the console.

Expected behavior
The plugin should produce a concise, easy to understand error or series of errors and abort the bundle.

Additional information
Here's the code in question:
https://github.com/bumble-org/rollup-plugin-chrome-extension/blob/0a4499fb049205540e9f4523541487b980786f33/src/manifest-input/index.ts#L397-L403

Cannot import @ffmpeg/ffmpeg

Describe the bug

Cannot import @ffmpeg/ffmpeg.

How do we reproduce?

  1. git clone "https://github.com/kyrelldixon/svelte-tailwind-extension-boilerplate.git"
    cd svelte-tailwind-extension-boilerplate
    yarn; yarn add @ffmpeg/ffmpeg; yarn add -D @rollup/plugin-json
  2. rollup.config.js
    import json from "@rollup/plugni-json";
    // ...
    export default {
      // ...
      plugins: [
         // ...
         json()
      ]      
    };
  3. src\background\index.js
    import { createFFmpeg } from "@ffmpeg/ffmpeg";
    export {};

Expected behavior

Be able to import @ffmpeg/ffmpeg

Actual behavior

rollup v2.36.2
bundles src/manifest.json → dist...
[!] (plugin chrome-extension) Error: Could not load background\util (imported by background\index.js): Could not load: background\util
Error: Could not load background\util (imported by background\index.js): Could not load: background\util
    at Object.load (C:\repositories\extensions\svelte-tailwind-extension-boilerplate\node_modules\rollup-plugin-chrome-extension\src\mixed-format\resolveFromBundle.ts:29:1)
    at C:\repositories\extensions\svelte-tailwind-extension-boilerplate\node_modules\rollup-plugin-chrome-extension\node_modules\rollup\dist\shared\node-entry.js:13117:25

Please complete the following information:

  • Library Version: 3.5.2
  • Operating System: Windows 10 Pro 21H1
  • Browser: Irrelevant, since the error occurs at the build time
  • Node Version: 14.17.5

Additional context

Adding json() to rollup.config.js is crucial, because for some reason, @ffmpeg/ffmpeg will attempt at some point to load up @ffmpeg/ffmpeg's package.json

Inline source maps stopped working since v3.5.x

Google search terms

rollup inline sourcemap

Describe the bug

Upgrading from version 3.4.0 to version 3.5.1 or higher leads to no sourcemap being output. When I search the build directory I don't find source map files or comments.

How do we reproduce?

rollup.config.js:

import { chromeExtension } from 'rollup-plugin-chrome-extension';

export default (async () => {
  return {
    input: 'src/manifest.json',
    output: {
      dir: 'build',
      format: 'esm',
      sourcemap: 'inline',
    },
    plugins: [
      chromeExtension(),
    ],
  };
})();

Expected behavior

Source files appear in the src/ directory of the Sources tab of the Chrome developer tools

Actual behavior

Only bundled .js files appear and they contain no source map URL.

Screenshots

v3.4.0 (correct)

Screen Shot 2021-03-22 at 2 41 54 PM

v3.5.4 (incorrect)

Screen Shot 2021-03-22 at 2 42 57 PM

Please complete the following information:

  • Library Version: 3.5.x
  • Operating System: macOS 11.2.3 (20D91)
  • Browser: Chrome 89.0
  • Node Version: v14.11.0

Additional context

Downgrading to ~3.4.0 fixes the problem.

setting page_action in manifest is not allowed

adding page_action in the manifest will return
[!] (plugin chrome-extension) Error: There were problems with the extension manifest.

page_action

  "page_action": {
    "browser_style": true,
    "default_icon": {
      "19": "assets/icons/icon-16.png",
      "38": "assets/icons/icon-38.png"
    },
    "default_title": "Whereami?"
  },

refs

Reloader fails when Firebase is used in Chrome extension

The push reloader is unable to authenticate with Firebase when the Chrome Extension project has another version of Firebase installed. The conflicting versions of Firebase cause Firebase's postinstall hook to partially install itself.

A quick fix is to delete the folder node_modules/rpce-push-reloader/node_modules/@firebase. This will cause node to resolve to the main correctly installed folder node_modules/@firebase.

A technically safe fix is to use [email protected], the same version as rpce-push-reloader, but this is not a great long term solution.

Support for `devtools_page` field in `manifest.json`

@jacksteamdev
Please add support for devtools_page field in manifest.json. Currently, it just ignores it and can't handle devtools functionality of an extension.

It would be really nice! Say me if I can participate in it. It is important for my project.
I look forward to hearing!

How might I modify the rollup.config.js to add a "run local" script?

Due to the performance of my extension, I would like the script option to build and run a local server. Long story short: I need to build new pages/components, but reloading via the extension has a lot going on and it is therefore slow.

How would the config be built so that it would serve ./dist on localhost

Using `web_accessible_resources` to copy the official i18n `_locales` folder removes the `_`

Google search terms

rollup-plugin-chrome-extension web_accessible_resources _locales

Describe the bug

How do we reproduce?

  1. Create a src/_locales/en/messages.json file (specs)
  2. Add the folder to src/manifest.json:
{
  "web_accessible_resources": ["_locales/**/*.json"]
}

Expected behavior

src/_locales/**/*.json being copied to dist/_locales.

Actual behavior

src/_locales/**/*.json being copied to dist/locales.

Screenshots

image

Please complete the following information:

  • Library Version: 3.5.7
  • Operating System: macOS 11.4
  • Browser: unrelated
  • Node Version: 14.17.1

Additional context

Should be pretty straightforward.

Is compatible for Vite?

Is your feature request related to a problem? Please describe.

I am using vite and vue3 to build a chrome extension. I would like using this plugin to bundle codes. I try to add this plugin in vite and find it not compatible.

Describe the solution you'd like

Vite has given a compatible solution described here

Describe alternatives you've considered

Additional context

Support firefox / cross browser compatibility

Is your feature request related to a problem? Please describe.

No issue per-say but this rollup plugin would benefit people greatly if it worked in firefox as well.

Describe the solution you'd like

To be able to develop cross-browser extensions using only this plugin. There is a fork already for webextension-polyfill, which is the basis of cross-browser extension development

Describe alternatives you've considered

I've already done a rollup configuration that allows development of firefox plugins but only by importing every file separately. This would make it so much faster to create browser extensions

TSX content script file extension makes [name]-[hash].tsx output file in dist

Google search terms

I tried latest @rollup/plugin-typescript and rollup-plugin-typescript2 in case it was the typescript plugin.

Describe the bug

Specifying a TSX file in content_scripts creates a file in dist/assets with a TSX extension instead of JS. The contents of the file don't need to actually have React, just the .tsx extension is enough to trigger the issue.

How do we reproduce?

Change the line here to end in .tsx and rename the associated file to end with .tsx, and build w/ rollup -c.

Expected behavior

No typescript files in the dist folder

Actual behavior

image

The contents of the file seem off as well:

(function () {
	'use strict';

	const importPath = /*@__PURE__*/JSON.parse('"../content/index.tsx"'); // 👈 extension here is wrong i think

	import(importPath);

}());

Note, though, the expected file in dist/content/index.js is correct. ¯\(ツ)

Screenshots

output:
image
no build errors:
image

Please complete the following information:

  • Library Version: 3.5.3
  • Operating System: Mac OS Big Sur
  • Browser: Chrome
  • Node Version: v14.15.4

Additional context

P.S. thank you for this library, it is just so so much better than anything else I've found, primarily the same 3 year old tutorial being reposted over and over. The live reloading alone is worth gold.

Incorrectly reloading extension

Describe the bug

After the Rollup configurations re-run, simplerReload() doesn't reload the background page.

How do we reproduce?

  1. Have a background script.
  2. Apply any modification that would trigger the Rollup configurations to re-run.
  3. The extension will auto-reload, but inspecting the background page reveals an error of the form:
    background-page-reloader-2453c4f4.js:1 Failed to load resource: net::ERR_FILE_NOT_FOUND
    

Expected behavior

Reload the background page.

Please complete the following information:

  • Library Version:: 3.5.2
  • Operating System: Windows 10 x64 21H1
  • Browser: Google Chrome Canary 94.0.4584.0
  • Node Version: 14.7.3

Additional context

I realized that it has to do specifically with not reloading the background page because when manually reloading, the extension does load as usual., rather than throw the same error.

Use Rollup context to warn or error

Is your feature request related to a problem? Please describe.
Rollup plugins should not throw errors or use the console. Instead, they should use this.warn or this.error.

Describe the solution you'd like
We should refactor to remove console logs and throw statements, and we should catch any errors we can forsee.

Describe alternatives you've considered
None.

Additional context
this.error on rollupjs.org

Use postcss to compile styles

Is your feature request related to a problem? Please describe.

It looks like the plugin lacks the capability to compile the .less files.

The manifest.json looks like the below:

...
"content_scripts": [{
    "css": [
      "styles/content.less"
    ],
  }],
...

After building, the .less suffix remains unchanged in the output manifest.json and less files are not compiled.

Describe the solution you'd like

Support less file compilation

Describe alternatives you've considered

I may use external plugin for less compilation, such as rollup-plugin-less. The usage should be like typescript compilation.

{
    input: "manifest.json",
    output: {
      dir: "dist",
      format: "esm",
    },
    plugins: [
      chromeExtension(),
      simpleReloader(),

      typescript(),
      less(),
      
      resolve(),
      commonjs()
     ]
}

Additional context

Cannot import content scripts

Google search terms

Didn't try to Google the issue, but rather to look into boilerplate examples

Describe the bug

If I try to import the files like so:

{
  "content_scripts": [
    {
      "matches": ["https://example.com/*"],
      "js": [
         "lib/some-library.js",
         "scripts/content-script.js"
       ]
    }
  ]
}

Then the output of lib/some-library.js will be empty.
Otherwise, if I do:

{
  "content_scripts": [
    {
      "matches": ["https://example.com/*"],
      "js": ["scripts/content-script.js"]
    }
  ]
}

scripts/content-script.js

import { someFunction } from "../lib/some-library";

The output will be:

{
  "web_accessible_resources": [
    "some-library-cd51b70d.js",
    "scripts/content-script.js"
  ]
}

What will be imported in scripts/content-script.js:

import { someFunction } from "../some-library-cd51b70d-c791af63.js";

Because the filename to be imported is different from the one that actually exists, it will fail.

How do we reproduce?

Simply create 2 content scripts that need to be linked and import one's function/variable/whatever into the other.

Expected behavior

It should work correctly.

Actual behavior

It imports a different filename than there actually is.

Please complete the following information:

  • Library Version: ^3.5.1
  • Operating System: Windows 10 20H2 build 19042.685
  • Browser: Chromium Edge 88.0.705.29
  • Node Version: 14.15.3

Additional context

rollup.config.js

import {
  chromeExtension,
  simpleReloader
} from "rollup-plugin-chrome-extension";
import { terser } from "rollup-plugin-terser";
import { emptyDir } from "rollup-plugin-empty-dir";
import zip from "rollup-plugin-zip";
import resolve from "@rollup/plugin-node-resolve";

const isProduction = !process.env.ROLLUP_WATCH;

export default {
  input: "src/manifest.json",
  output: {
    dir: "dist",
    format: "esm"
  },
  plugins: [
    // always put chromeExtension() before other plugins
    chromeExtension(),
    !isProduction && simpleReloader(),
    resolve(),
    emptyDir(),
    isProduction && terser(),
    isProduction && zip({ dir: "dist_packed" })
  ]
};

[!] Error: Invalid substitution "../node_modules/nsfwjs/dist/index" for placeholder "[name]" in "output.entryFileNames" pattern, can be neither absolute nor relative path.

Google search terms

rollup Error: Invalid substitution " for placeholder "[name]"

Describe the bug

When building getting an error saying :

[!] Error: Invalid substitution "../node_modules/nsfwjs/dist/index" for placeholder "[name]" in "output.entryFileNames" pattern, can be neither absolute nor relative path.

How do we reproduce?

Clone and checkout on: https://github.com/maifeeulasad/chrome-sfw/tree/24da719df455e17eddbb148126af5b3234388573

Expected behavior

It used to work. I mean build without error.

Actual behavior

Screenshots

Please complete the following information:

  • Library Version: ^3.5.2
  • Operating System: Ubuntu 20.04 LTS
  • Browser: 91.0.4472.106 (Official Build) (64-bit)
  • Node Version: v14.17.1

Additional context

Found something here: https://github.com/alfredosalzillo/rollup-plugin-multi-input

But this is not even on my dependency.

Background scripts are unable to respond messages asynchronously

Google search terms

rollup chrome extension plugin async messages background script

Describe the bug

Compiling an extension with the plugin causes background scripts to be unable to respond messages using sendResponse, when receiving a single with chrome.runtime.onMessage.addListener().

How do we reproduce?

Creating an extension with these files:

contentScript.js

chrome.runtime.sendMessage({'test':'test'}, result => result && alert(result))

background.js

chrome.runtime.onInstalled.addListener(function() {
  chrome.runtime.onMessage.addListener(
    (request, sender, sendResponse) => {
      setTimeout(() =>{
        sendResponse('it works')
      }, 500)
      return true
    }
  );
});

I've created a repo with the manifest.json and rollup.config.js files. You can clone it and replicate the issue.

Expected behavior

In the case above, an alert with the message 'it works' should pop up. Note that that's what happens if using the extension uncompiled.

Actual behavior

The port gets closed when it's not supposed to.

Screenshots

image

Please complete the following information:

  • Library Version: 3.2.0
  • Operating System: macOS 10.14.6
  • Browser: Chrome 83.0.4103.116
  • Node Version: 14.2.0

Additional context

Support persistent background pages with specific import wrapper

Is your feature request related to a problem? Please describe.

Persistent background pages don't need much event capturing, just runtime.onInstalled. We should either adapt the explicit import wrapper, or make a special one.

Use case: chrome.webRequest is not compatible with event pages (persistent: false).

Describe the solution you'd like

We should probably just force the background page to be persistent when this permission is being used.

Also, if the background page is persistent, then we don't need to capture events. In this case we should just use the simple wrapper that the content scripts use.

Describe alternatives you've considered

NA

Additional context

See #44 and #45

Putting webRequest / webRequestBlocking in manifest makes the backend-script crash

Google search terms

rollup plugin chrome webrequest No matching signature

Describe the bug

I tried to add webRequest / webRequestBlocking rights to my manifest,
then when i launch my extension after a npm run watch i have to following error in my console:
Uncaught TypeError: No matching signature.

After some investigations it seems to comes from the line
event.addListener(handleEvent); in the generated background-script. The event is a WebRequestEvent and the listener must have a second parameter with the URL to match and it also have a 3rd optional parameter.
In my case the params are :

  chrome.webRequest.onBeforeRequest.addListener(
    proxyCallback,
    {
      urls: [
        'chrome-extension://*/api/*',
        'chrome-extension://*/private-api/*',
        'http://*/api/*',
        'http://*/private-api/*',
      ],
    },
    ['blocking']
  );

If i change manually the generated background-script to:

     if (event.constructor.name !== 'WebRequestEvent') {
        event.addListener(handleEvent);
      } else {
        console.log('event not captured');
      }

the extension works well but i'm not sure about the side effects ^^

How do we reproduce?

add

    "webRequest",
    "webRequestBlocking"

to the manifest.json permission's part

Expected behavior

extension shouldn't crash

Actual behavior

already described

Please complete the following information:

  • Library Version: rollup-plugin-chrome-extension": "3.1.0",
  • Operating System: macOS
  • Browser: Chrome
  • Node Version: 14.0.0

Duplicate assets produce a warning

Describe the bug
Rollup emits a warning when the manifest and an HTML file reference the same asset.

To Reproduce
Steps to reproduce the behavior:

  1. Configure a manifest with an image and an HTML file that uses the same image.
  2. Configure and run Rollup.
  3. See the warning: The emitted file "options.jpg" overwrites a previously emitted file of the same name

Expected behavior
The asset should be read from disk and emitted once with no warnings.

Additional context
This probably isn't a real problem since the overwritten file is the same as the previous file, but it could impact performance in extensions that have several HTML files. Also, the warning is extra noise that devs don't need to think about.

Manifest v3

Is your feature request related to a problem? Please describe.

It's not a problem yet, but it will become one in the future.
Manifest v2 will become deprecated at some point, which will be replaced by Manifest v3.
I watched a little bit of the Chrome Dev Summit, and there I heard that the first version of Manifest v3 will hit Chrome Canary (I believe) around mid-January 2021.

Describe the solution you'd like

Begin reworking the plugin on a separated branch and make it to be the master branch when Manifest v2 will go deprecated.
FYI, Google has made a migration guide.

Support alternative manifest formats

Is your feature request related to a problem? Please describe.
It would be nice to be able to put comments in manifest.json or to use manifest.ts.

Describe the solution you'd like
The manifest input should use JSONC to parse manifests, and should also parse TS/JS files. The plugin should export a ChromeExtensionManifestV2 interface.

Describe alternatives you've considered
YAML files are currently supported but VS Code schema auto-completion just isn't there yet.

Additional context
Relevant code:

https://github.com/bumble-org/rollup-plugin-chrome-extension/blob/0a4499fb049205540e9f4523541487b980786f33/src/manifest-input/index.ts#L48

https://github.com/bumble-org/rollup-plugin-chrome-extension/blob/0a4499fb049205540e9f4523541487b980786f33/src/manifest-input/index.ts#L144-L157

Possibly benign version warnings

Describe the bug

When using latest versions of rollup plugins, I get the following npm warnings:

pm WARN [email protected] requires a peer of @rollup/plugin-commonjs@^11.0.2 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of rollup@^1.31.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of rollup@^1.6.0 but none is installed. You must install peer dependencies yourself.

This appears to be benign though, all the features of rollup-plugin-chrome-extension (eg. autoloading, building based on manifest.json) still work.

How do we reproduce?

List of devDependencies in package.json:

        "@rollup/plugin-commonjs": "^13.0.0",
        "@rollup/plugin-node-resolve": "^8.1.0",
        "@rollup/plugin-typescript": "^5.0.0",
        "@types/chrome": "0.0.117",
        "prettier": "^2.0.5",
        "rollup": "^2.18.1",
        "rollup-plugin-chrome-extension": "^3.1.0",
        "rollup-plugin-empty-dir": "^1.0.4",
        "typescript": "^3.7.4",
        "webextension-polyfill-ts": "^0.18.0"

Please complete the following information:

  • npm version: 6.14.4

simpleReloader auto closes tab with popup.html

Google search terms

chrome extension popup reload

Describe the bug

When popup.html is open in a separate tab - chrome-extension://id_of_application/popup.html, simpleReloader causes the tab to close instead of being reloaded.

How do we reproduce?

Open extension popup in new tab - chrome-extension://id_of_application/popup.html

Expected behavior

Tab with popup should reload (or at least stay opened)

Actual behavior

Tab with popup is closed when extension reloads via simpleReloader

Screenshots

Please complete the following information:

  • Library Version: 3.5.4
  • Operating System: MacOS 10.14.6
  • Browser: Chrome 89.0.4389.90
  • Node Version: 14.4.0

Additional context

Content script is emitted as an empty chunk

Google search terms

rollup content script web extension

Describe the bug

When using a content script to inject code into the webpage from the extension, the content script, defined in the rollup.config.js as

    input: "src/libs/content.js",
    output: {
      sourcemap: true,
      format: "iife",
      name: "content",
      file: "public/build/content.bundle.js",
    }

is generated in the public/build folder correctly. However when it's finally copied to the list folder, this message comes up

(!) Generated an empty chunk
build/content.bundle

and the content.bundle.js, which has the appropriate code inside of it in the build folder, now is blank in the dist folder.

How do we reproduce?

specify a content script area in the manifest

  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": ["build/content.bundle.js"]
    }
  ]

write code into the content script located at src/libs (or whatever folder you use to house your JS)/content.js

Expected behavior

The content script should be bundled, and copied to the dist folder ready for the extension to inject into the webpage

Actual behavior

The content.bundle.js emitted in the dist folder is blank.

Please complete the following information:

  • Operating System: MacOS
  • Browser: Chrome
  • Node Version: 14.12.0

Add an escape hatch for manifest validation

Is your feature request related to a problem? Please describe.

It is possible for the manifest JSON schema to contain errors. This would prevent a build from completing successfully.

Describe the solution you'd like

There should be an option to skip validation, maybe options.validateManifest

Describe alternatives you've considered

Additional context

The same `dynamicImportWrapper` is used for background and content scripts

Describe the bug
The module loader emits the same scripts for both background and content scripts. This isn't a big deal, but it might delay content script loading.

To Reproduce
Steps to reproduce the behavior:

  1. Bundle a Chrome extension
  2. Look at the module loader scripts added to background.scripts and content_scripts.
  3. Both scripts wrap wake events

Expected behavior
Content scripts should not do anything with events, since they don't sleep.

Additional context
Relevant code:

https://github.com/bumble-org/rollup-plugin-chrome-extension/blob/0a4499fb049205540e9f4523541487b980786f33/src/manifest-input/index.ts#L331-L347

Source maps don't work for typescript

Describe the bug
Source maps throw an error in the console:
DevTools failed to load SourceMap: Could not load content for chrome-extension://dhkkfbogdjlaiokeknpkpdkogcahamhe/popup/popup.js.map: HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME

To Reproduce
The following rollup.config.js:

export default {
    input: 'src/manifest.json',
    output: {
        dir: 'dist',
        format: 'esm',
        sourcemap: true,
    },
    plugins: [
        chromeExtension(),
        simpleReloader(),
        typescript({include: 'src/**/*.ts', sourceMap: true}),
        resolve(),
        commonjs(),
    ],
}

Expected behavior
Source maps are linked automatically.

Versions:

  • OS: MacOS Catalina

  • Browser: Chrome 83

    "@rollup/plugin-commonjs": "^11.1.0",
    "@rollup/plugin-node-resolve": "^8.0.1",
    "@rollup/plugin-typescript": "^4.1.2",
    "rollup": "^1.32.1",
    "rollup-plugin-chrome-extension": "^2.2.1",
    "typescript": "^3.7.4",
    "webextension-polyfill-ts": "^0.12.0"

prettier dependency?

https://github.com/extend-chrome/rollup-plugin-chrome-extension/blob/5722a521d8a6be714e3a0fc98b253e22f4277bc4/package.json#L44

I discovered today that this entry was at the root of problems I was having with code formatting, as it was blocking use of project-level .prettierrc used to format Svelte.

By removing the above line, removing package-lock.json, and then re-running npm i, *.svelte are now formatted as expected.

Expected Behavior / Situation

All levels of Svelte files are code formatted.

Actual Behavior / Situation

Code inside <script> tags is ignored by code formatting.

Modification Proposal

I don't know the code well enough to say what could keep this prettier dependency from leaking out.

Manifest v2 options_ui isn't bundling associated files

Google search terms

Google terms for chrome extension options page and options_ui with rollup.

Describe the bug

Chrome (and other browsers) provide two methods to specify an options page for users.
See official documentation here: https://developer.chrome.com/extensions/options

This is achieved by specifying a reference to an options page in manifest.json using either:

  1. options_page (open options in a new tab)
  2. options_ui (show options as a native UI popup on extensions page)

At the moment (v3.3.0) the first method (options_page) works. The second option unfortunately does not work.

How do we reproduce?

This issue relates to Manifest version 2.

  1. Create options.html and options.js files in the root directory (use the Chrome examples)
  2. Add options_ui to manifest.json
"options_ui": {
    "page": "options.html",
    "open_in_tab": false
  },

Expected behavior

In the case of options_page the options.html and associated JS and CSS are copied into the dist bundle. The same behaviour should apply for options_ui if present in manifest.json.

Actual behavior

At the moment, only the options_page method works. It would be great to have the second options_ui supported too.

Screenshots

Please complete the following information:

  • Library Version: 3.3.0
  • Operating System: MacOS Catalina
  • Browser: Chrome version 84.0.4147.105 (Official Build) (64-bit)
  • Node Version: 12.18.3

Additional context

The solution may simply be a matter of including options_ui into derivedFiles HTML array around here
https://github.com/extend-chrome/rollup-plugin-chrome-extension/blob/53de0949378e7b6ab3866a6f671d9c3dc72407f2/src/manifest-input/manifest-parser/index.ts#L71

Semi related to Issue 27

Reloading requires restarting rollup and extension

Describe the bug

In order to get my code to reload in either the popup window or the background page, I have to both:

  • Ctrl+C and restart rollup
  • flip the extension from disabled to enabled

If I don't do either of those steps then my new code is not actually run.

To Reproduce

The following rollup.config.js:

export default {
    input: 'src/manifest.json',
    output: {
        dir: 'dist',
        format: 'esm',
        sourcemap: true,
    },
    plugins: [
        chromeExtension(),
        simpleReloader(),
        typescript({include: 'src/**/*.ts', sourceMap: true}),
        resolve(),
        commonjs(),
    ],
}

The following manifest.json (revelant sections):

  "background": {
    "scripts": [
      "background/background.ts"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "assets/icon.png",
    "default_popup": "popup/popup.html"
  },

(Note: popup.html has a script tag pointing to popup.ts)

Run rollup -c -w

Expected behavior

For popup: I expect that after changing the code, it will rebuild and then next time I click the popup the new code will run.

For background page: I expect that after changing the code, it will restart the background page with the new code.

Versions:

  • OS: MacOS Catalina

  • Browser: Chrome 83

    "@rollup/plugin-commonjs": "^11.1.0",
    "@rollup/plugin-node-resolve": "^8.0.1",
    "@rollup/plugin-typescript": "^4.1.2",
    "rollup": "^1.32.1",
    "rollup-plugin-chrome-extension": "^2.2.1",
    "typescript": "^3.7.4",
    "webextension-polyfill-ts": "^0.12.0"

Additional context
Love the minimal setup of this build, hoping we can get it to work 🤞

Support copying over files not listed in the manifest

Is your feature request related to a problem? Please describe.

In a normal circumstance, the developer would want a content script to be loaded as usual.
However, in my use-case, I need to be able to inject a whole script directly into a web page to use the JavaScript that lives on that page.
More specifically, I made a YouTube Speed Control extension and I wish to replace its setup with Rollup, hopefully using this plugin.

Describe the solution you'd like

Have the ability to copy over any JavaScript file, regardless if it's listed in the manifest, or let the developer manually list files that are required to be copied-over.

Describe alternatives you've considered

I tried listing that script in the content script array, and it does execute as usual, but since the script relies on a function that lives in the page itself, it won't really work, or at least not cleanly, as I constantly need to check for the function's existence.

Additional context

In my use-case, I rely on YouTube's .setPlaybackRate() function as it's the most reliable and clean way for my extension to work.
Basically, once the content script loads up, it sends a message to the background, which fetches the script-to-be-injected, and the content script injects that script, after which the script takes the wheel and changes the speed of the YouTube player according to the user's preference.

Using Svelte

I wish to use Svelte with Svelte Materialify in my browser extension.
In my specific case, I only have a popup page, so I wish to use these there.
This is an example repo.
Basically, so far I am able to load up JavaScript, but not any styles, and I'm not sure what Rollup configuration is missing.

Error when rollup.config has more than one input file

Describe the bug
I have a bunch of images that are handled from JS (no img tag in html). Rollup doesn't include them in the dist directory.
When I add them to 'input' in rollup.config I get this error

[!] TypeError: RollupOptions.input must be a single Chrome extension manifest.

To Reproduce
Steps to reproduce the behavior:
create rollup.config with

export default {
    input    : ['src/manifest.json'],
    ...
}

Expected behavior
Input can be declared as an array, and all entries other than manifest.json are processed as rollup normally does.

Cannot copy format `png`

How to reproduction

git clone https://github.com/Himself65/better-zhihu
cd better-zhihu
yarn
rollup -c

and you will find that there is no icon.png on dir dist, but

{
  "icons": {
    "128": "static/icon.png"
  }
}

Use static analysis to detect wake events

Is your feature request related to a problem? Please describe.
The way we handle wake events is not very dev-friendly. If the extension uses a wake event, the developer must remember to configure the plugin to include those events in the background module loader.

Describe the solution you'd like
The plugin should statically analyze the background script for wake events and include only those events in the module loader. We can probably use an AST for this.

Describe alternatives you've considered
Dynamic event detection isn't a great alternative for the long run. It's easy to implement, but will cause a delay each time the background page activates.

Plugin throws when manifest contains no scripts

Describe the bug
A manifest with no scripts and no HTML files causes Rollup to throw.

To Reproduce
Steps to reproduce the behavior:

  1. Create a manifest.json with no scripts and no HTML files.
    https://github.com/bumble-org/rollup-plugin-chrome-extension/blob/2d878a76967b4daf757670135bf6a9ab5a191379/__fixtures__/extensions/no-scripts/manifest.json#L1-L9
  2. Configure and run Rollup.
  3. See error: 'A Chrome extension must have at least one script or HTML file.'

Expected behavior
Rollup should bundle the extension without any complaints.

Additional context
This happens because options.input is replaced with an empty object in both composed manifest-input and html-inputs plugins, since there are no scripts to bundle. This problem will become more common when we adopt the new this.emitFile API for chunks, so we need to fix this eventually.

Both plugins should probably emit a placeholder script in the event that there are no scripts to emit after parsing the manifest or HTML files. All assets should be emitted as usual.

Inconsistent readme

Describe the bug
There are some mistakes in the readme:

Create a rollup.config.js file in your project root.

// rollup.config.json

js or json?

Add these scripts to your project.json file.

// package.json

project.json or package.json?

Relative parent paths to icons in manifest fail to build

Google search terms

[!] (plugin chrome-extension) Error: The "fileName" or "name" properties
of emitted files must be strings that are neither absolute nor relative
paths and do not contain invalid characters, received "../example.png"

rollup-plugin-chrome-extension icons

rollup-plugin-chrome-extension images in manifest

Describe the bug

When using a relative path of the format "../images/example.png" Rollup fails to properly resolve images.
Moving the image folder to the same directory as the manifest.json and removing the "../" allows images to be copied over correctly.

How do we reproduce?

  1. add an image in the parent folder of manifest.json
  2. add an image path to manifest.json, e.g. "icons": { "16": "../example.png" }
    • include a "../" relative portion in the path
  3. attempt to yarn start or yarn build

Expected behavior

I expected to be able to reference images in a parent directory.

Actual behavior

Got an error:
[!] (plugin chrome-extension) Error: The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "../example.png"

Workaround:

Moving images to not require a ../ relative path allows them to resolve correctly.

Please complete the following information:

  • Library Version: 3.5.3
  • Operating System: macOS 10.14.6
  • Browser: Chrome 88.0.4324.192
  • Node Version: Node v12.16.2

When default_popup is not configured, rollup will not bundle it

Google search terms

Describe the bug

When default_popup is not configured, rollup will not bundle it,but i want to use chrome.windows.createcreate this popup.

chrome.windows.create({
      url: 'pages/popup/index.html',
})

How do we reproduce?

  1. in background.js
console.log('background script12')
let currentId = null

chrome.browserAction.onClicked.addListener(function (tab) {
  var w = 1000;
  var h = 600;
  var left = Math.round((screen.width / 2) - (w / 2));
  var top = Math.round((screen.height / 2) - (h / 2));
  if (currentId) {
    chrome.windows.update(currentId, {
      focused: true
    })
  }else {
    chrome.windows.create({
      url: 'pages/popup/index.html',
      width: w,
      height: h,
      focused: true,
      'left': left,
      'top': top,
      type: 'popup'
    }, window => {
      currentId = window.id
    });
  }
  
});
  1. in manifest.json, clear browser_action

Expected behavior

Actual behavior

Screenshots

image

Please complete the following information:

  • Library Version: 3.5.6
  • Operating System: Mac
  • Browser: Chrome
  • Node Version: 14

Additional context

Missing "dynamic import wrapper" section in README

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

In README.md, the following section mentions the dynamic importer for importing modules into the background.js page:

⭐️ Use ES2015 Modules In Your Scripts
Chrome extensions don't support modules in background and content scripts. We've developed a [module loader](https://github.com/extend-chrome/rollup-plugin-chrome-extension#dynamic-import-wrapper) specifically for Chrome extension scripts, so you can take advantage of Rollup's great code splitting features.

However, the link to the "dynamic import wrapper" anchor doesn't go anywhere on the page, and that section seems to be missing altogether in the README.

Your Proposal for Changes

I'd love to see this portion of the README fleshed out, maybe with an example? I want to use this feature in my background.js, but I don't really know where to start — having this reference fixed would help those of us who are new to the project.

The simple reloader only works in MV3 if a content script is open

The simple reloader works by polling a timestamp file in the background. In MV2, the background page would stay open and allow us to just use setInterval to fetch the file. In MV3, the background is a service worker, and service workers have a very short lifespan. Timers do nothing to keep a service worker alive.

In order to keep our service worker open and checking that timestamp, the simple reloader adds some code to your content scripts to open a message port to the background. This will keep a service worker alive for ~5 minutes.

This works, but ONLY if a content script is open. We could add similar functionality to the extension HTML pages (popup, options, etc...), but I want to dedicate most of my efforts in the near future to making this Rollup plugin Vite compatible. This would add true HMR to at least the HTML pages, and hopefully to content scripts. There's more than one blocker for Vite compatibility, but I think we can get past them without too much work.

If Vite turns out to be out of reach, we'll revisit the simple reloader and try to get it working better.

Push reloader is broken: "Uncaught FirebaseError"

Describe the bug
The automatic reload functionality is broken, and not entirely sure how to fix this issue.

To Reproduce
Steps to reproduce the behavior:

  1. Invoke the npm watch script, (rollup -c -w)
  2. I see the following console log messages in the background.html console:

reloader-sw-13ddda07.js:245 Uncaught FirebaseError: Installations: Missing App configuration value: "projectId" (installations/missing-app-config-values). at getMissingValueError (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:2090:32) at extractAppConfig (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:2071:27) at Component.instanceFactory (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:3117:13) at Provider.getOrInitializeService (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:816:43) at Provider.getImmediate (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:720:37) at Component.factoryMethod [as instanceFactory] (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:5305:72) at Provider.getOrInitializeService (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:816:43) at Provider.getImmediate (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:720:37) at FirebaseAppImpl._getService (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:1252:53) at FirebaseAppImpl.messaging (chrome-extension://baofmnngiegejbkmjldhlojijmfkpolh/assets/reloader-sw-13ddda07.js:1461:43)

Expected behavior
The background script should automatically reload.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome 81.0.4044.138
  • rollup-plugin-chrome-extension version 2.2.0

Additional context
Add any other context about the problem here.

Adding Cheerio to chrome extension using this plugin causes an exception

Describe the bug
I am using the following:

// rollup.config.js
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'

import {chromeExtension} from 'rollup-plugin-chrome-extension'

export default {
  input: 'src/manifest.json',
  output: {
    dir: 'dist',
    format: 'esm',
  },
  // always put chromeExtension() before other plugins
  plugins: [
    chromeExtension(),
    resolve(),
    commonjs()
  ],
}
background.js
import cheerio from 'cheerio'

console.log('background service running');

chrome.browserAction.onClicked.addListener(buttonClicked);

function buttonClicked(tab) {
  console.log('activate');
  chrome.tabs.sendMessage(tab.id, 'activate');
}

chrome.runtime.onMessage.addListener((message, sender) => {
  console.log(message);
  if (message.title === 'open') {
    const doc = cheerio.load(message.url);
    console.log(doc);
    chrome.tabs.create({url: message.url})
  }
});

This exception appears when I yarn build

src/manifest.json → dist...
[!] Error: Unexpected token (Note that you need rollup-plugin-json to import JSON files)
node_modules\cheerio\package.json (2:8)
1: {
2:   "name": "cheerio",
           ^
3:   "version": "1.0.0-rc.3",
4:   "description": "Tiny, fast, and elegant implementation of core jQuery designed specifically for the server",
Error: Unexpected token (Note that you need rollup-plugin-json to import JSON files)
    at error (D:\workspace\get-magnet\node_modules\rollup\dist\rollup.js:5330:30)
    at Module.error (D:\workspace\get-magnet\node_modules\rollup\dist\rollup.js:9612:9)
    at tryParse (D:\workspace\get-magnet\node_modules\rollup\dist\rollup.js:9524:16)
    at Module.setSource (D:\workspace\get-magnet\node_modules\rollup\dist\rollup.js:9841:33)
    at D:\workspace\get-magnet\node_modules\rollup\dist\rollup.js:12622:20
    at async Promise.all (index 2)
    at async Promise.all (index 0)
    at async Promise.all (index 0)
    at async Promise.all (index 0)
    at async Promise.all (index 0)

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

To Reproduce
Steps to reproduce the behavior:

  1. Following the instructions on the readme
  2. yarn add cheerio
  3. reference cheerio somewhere in either background or content
  4. yarn build

Desktop (please complete the following information):

  • OS: Win 10

Additional context
I followed the read general instructions from the readme and it was working fine till I added cheerio. I tried adding rollup-plugin-json but that gave a ton of warning and threw execptions when loading into chrome.

Migrate to @extend-chrome

We're migrating this library over to a new and more aptly named organization: extend-chrome!

TODO

  1. Catalog bumble-org dependencies
  2. Update README.md
  3. Update package.json
  4. Transfer GitHub repo
  5. Transfer NPM package

import path incorrect after yarn build after folllowing readme

Describe the bug
I followed the read to get set up then I noticed that it was throwing an exception that it couldnt find one of the bundled files then I saw that the path was wrong for a win OS

This was generated
import('..\background.js').then(triggerEvents);

This is what should have been generated
import('../background.js').then(triggerEvents);

To Reproduce
Steps to reproduce the behavior:

  1. Follow readme instructions
  2. yarn build
  3. Try to load to chrome

Expected behavior
I expect the path to be compatible with whichever OS I am using.

Screenshots
image

Desktop (please complete the following information):

  • OS: win 10

Additional context
I had to install the ubuntu subsystem on to my windows 10 machine and ran yarn build in the mean time and it generates the path fine.

Cannot import NodeJS modules

Describe the bug

I want to make an extension that uses @ffmpeg/ffmpeg.
Except, by doing

import { createFFmpeg } from "@ffmpeg/ffmpeg";

in the background script, it apparently also attempts to import JSON(s).

If I add to rollup.config.js:

import json from "@rollup/plugin-json";

export default {
  // ...
  plugins: [
    chromeExtension(),
    json(),
    resolve(),
    commonjs(),
    emptyDir()
  ]
}

then, after running this Rollup configuration, inspecting the background page will reveal the following error:

Uncaught (in promise) TypeError: Failed to resolve module specifier "util". Relative references must start with either "/", "./", or "../".

How do we reproduce?

  1.  npx degit "kyrelldixon/svelte-tailwind-extension-boilerplate#main" your-extension-name
     yarn
     yarn add @ffmpeg/ffmpeg && yarn add -D @rollup/plugin-json
  2. Add the above snippets in the appropriate places.
  3. Run the Rollup configuration.
  4. Load the extension to Chrome.
  5. Inspecting the background page will reveal the above error.

Expected behavior

Being able to import @ffmpeg/ffmpeg without any problem.

Actual behavior

Getting the error above.

Please complete the following information:

  • Library Version:: 3.5.2
  • Operating System: Windows 10 x64 21H1
  • Browser: Google Chrome Canary 94.0.4584.0
  • Node Version: 14.7.3

Additional context

I made a sample project (without using rollup-plugin-chrome-extension) that does import both @ffmpeg/ffmpeg and uses @rollup/plugin-json.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.