June 19, 2022

How to Build Chrome Extension with Manifest v3 using Svelte - Boilerplate Included

In this article, I will explain how to build a chrome extension (from scratch) with manifest v3 using svelte. FYI, as an example, we will update google.com’s background colour using our chrome extension.

If you’re here for just the boilerplate, please feel free to get it from the following link. Otherwise, let’s dive in.

Table of Contents

Boilerplate:

https://github.com/viv3kc/Svelte-Boilerplate-for-Chrome-Extension

Setup our project:

First of all, let’s set up our project area:

npx degit sveltejs/template my-extension
cd my-extension
npm install
npm run dev

At this point, our svelte project is ready to use. But, we can make our extension a bit compact by adding the CSS in the bundle.js.

To emit CSS directly into bundle.js, let’s update our rollup config. In the rollup.config.js file add the emitCss: false inside the plugins.

plugins: [
    svelte({
      emitCss: false, // <- add this line to emit css into bundle.js
      compilerOptions: {
        // enable run-time checks when not in production
        dev: !production
      }
    }),

And, remove the following lines because we no longer need them.

import css from 'rollup-plugin-css-only'; // <- remove it

// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }), // <- remove it

Now, we can also remove the unnecessary CSS files:

  • public/bundle/bundle.css
  • public/global.css

Manifest v3

After setting up our project, we can now work on the chrome manifest file. In this guide, we will use version 3 which Google recommends.

Let’s add a new file called manifest.json in the public folder.

{

  "name": "Example",
  "description": "Description",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
    "matches": ["https://www.google.com/*", "https://google.com/*"],
    "js": ["build/bundle.js"],
    "run_at": "document_end"
  }]
}

Here, I have added a few properties to explain what is our extension trying to do.

  • Let’s focus on the following properties from our manifest file:
  • Manifest Version: mainfest_verion is required to add the version number. In our example, I’m using v3.
  • Background script: It is used to tell the extension which files to refer, to and how that file should behave. for example, if a tab has changed.
  • Content scripts: Content scripts are files that run in the context of web pages. For example, check for a specific website, when to run our script etc.

you can read more about these or additional properties on the [https://developer.chrome.com/docs/extensions/reference/?ref=ravensmove.com](chrome developer) page.

Background Script:

At this point, our manifest.json file is ready. So, let’s focus on the background.js file.

In background.js, we can call chrome APIs to check if the user has opened/changed any tab. So, whenever there is a tab update our script will send a message about it.

try {
  chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete') {
      chrome.tabs.sendMessage(tabId, {
        message: 'TabUpdated'
      });
    }
  });
} catch(e) {
  console.log("Error from Extension: ",e )
}

This tab update will allow us to check if the user is on google.com or not.

App.svelte

Now, Let’s capture the message from background.js inside the app.svelte.

Remove everything and add the following lines to check if the user is on the correct website.

<script>

  chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.message === 'TabUpdated') {
      let domain = window.location.hostname;
      domain = domain.replace('http://', '').replace('https://', '').replace('www.','').split(/[/?#]/)[0];

      if (domain !== "google.com") return

      setBackgoundColor();
    }
  });

</script>

Now, let’s add a function called setBackgroundColor that randomly generates colour and set it as the background of google.com

const setBackgoundColor = () => {
  const randomColor = Math.floor(Math.random()*16777215).toString(16);
  document.body.style.backgroundColor = "#" + randomColor;
}

Test the Chrome Extension:

To test our chrome extension, follow these steps:

  • Open extension tab in chrome i.e Three dots > More Tools > Extensions
  • Turn on the developer mode
  • Click on Load unpacked and then upload the public folder.

Now, if you reload the google, it will have a new background colour.

build-chrome-extension-with-svelte

Congratulation, you have successfully built your first chrome extension.

Things to consider:

  • Even though the svelte dev server automatically updates the public folder but we still have to manually reload the extension from the chrome.
  • If you’re planning to submit your extension to the web store, make sure to upload the production code by running npm run build

If you have any questions or need help with anything. Feel free to tweet @ravensmove.