How to create a chrome extension with svelte

01.08.2023

Did you ever want to create a chrome extension with svelte? Here is how!

Create SvelteKit Project

npm create svelte@latest

Select “skeleton project” and choose typescript

Add Tailwind

npx svelte-add@latest tailwindcss
pnpm i tailwindcss@latest

Add Extension adapter

pnpm i -D sveltekit-adapter-chrome-extension

Modify svelte config

import adapter from "sveltekit-adapter-chrome-extension";
import { vitePreprocess } from "@sveltejs/kit/vite";

const config = {
preprocess: [vitePreprocess({})],

    kit: {
    	adapter: adapter({
    		pages: "build",
    		assets: "build",
    		fallback: null,
    		precompress: false,
    		manifest: "manifest.json",
    	}),
    	appDir: "app",
    },

};

export default config;

Create layout file

Create a +layout.ts file inside src/routes/ and add the following

export const prerender = true

Create manifest.json

Create manifest.json inside your static folder and add the following:

{
	"manifest_version": 3,
	"name": "Some extension",
	"description": "The craziest extension on the internet",
	"version": "1.0.0",
	"chrome_url_overrides": {
		"newtab": "index.html"
	}
}

Build the project

npm run build

Installing the extension

  1. go to your browsers extension settings (chrome://extensions for chrome) and enable the developer mode
  2. select “Load Unpacked” and select the build folder inside your sveltekit project
  3. Hope that everything worked :smile:

More

Reset font size

Chrome extensions change the default font size to a smaller size, you can reset it to the default size with the following css code:

body {
	font-family: unset !important;
	font-size: unset !important;
}

Adding a popup

Create a new +page.svelte inside routes/popup

Modify your manifest.json to include the following:

{
	"action": {
		"default_title": "Crazy Popup",
		"default_popup": "popup.html"
	}
}

Getting user history

Installing chrome types

pnpm i -D @types/chrome

Add permissions to your manifest.json

{"permissions": ["history"]}

Access history in svelte

<script lang="ts">
	import { onMount } from "svelte";
	let history_items: chrome.history.HistoryItem[] = [];
	onMount(() => {
		let microsecondsPerWeek = 1000 * 60 * 60 * 24 * 7;
		let oneWeekAgo = new Date().getTime() - microsecondsPerWeek;
		chrome.history.search(
			{
				text: "", // Return every history item....
				startTime: oneWeekAgo, // that was accessed less than one week ago.
			},
			function (historyItems) {
				history_items = historyItems;
			}
		);
	});
</script>

{#each history_items as { title, url }}

<p>{title} - {url}</p>
{/each}