I am building a svelte browser extension, and in order to load images, I found out that I can use chrome.runtime.getURL(relative_path)
, which is well supported across browsers.
So, I wrote this code:
<img
src={chrome.runtime.getURL("image.png")}
alt={"an image"}
/>
When trying to build, I get:
transforming (8) node_modules/.pnpm/svelte@3.55.1/node_modules/svelte/transition/ind13:09:26 [vite-plugin-svelte] /MyComponent.svelte:17:9 'chrome' is not defined
15: <button on:click={handleOnClick}>
16: <img
17: src={chrome.runtime.getURL("image.png")}
^
18: alt={"an image"}
19: />
✓ 25 modules transformed.
I tried to polyfill this using webextension-polyfill
and @types/chrome
npm packages with no success.
My workaround:
I created this function
const polifillImg = (img: string) => {
// At build time this will be replaced by chrome.runtime.getURL(imgSrcBase + img)
return (
"__REPLACE_WITH_CHROME__" + imgSrcBase + img + "__CLOSING_PARENTESIS__"
);
};
Which I can now use like so:
<img
src={polifillImg("image.png")}
alt={"an image"}
/>
And in my vite.config.ts
:
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { replaceCodePlugin } from "vite-plugin-replace";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
replaceCodePlugin({
replacements: [
{ from: '"__REPLACE_WITH_CHROME__" + ', to: "chrome.runtime.getURL(" },
{ from: ' + "__CLOSING_PARENTESIS__"', to: ")" },
],
}),
svelte(),
],
});
Which, you know, works, but it is not great.
I would like to know how to correctly use the chrome
object the right way. Can someone show me the way?
Thanks