Skip to main content

Vue Content Scripts

CRXJS brings an authentic Vite HMR experience to content scripts. Let's add a Vue content script to your Chrome Extension.

Did you know?

A content script is JavaScript from a Chrome Extension that the browser executes on a designated web page. The page where the script runs is called the host page. The content script shares the DOM with the host page but has a separate JavaScript environment.

Add a content script

We declare content scripts with a list of JavaScript files and match patterns for the pages where Chrome should execute our content script. In manifest.json, create the field content_scripts with an array of objects:

manifest.json
{
// other fields...
"content_scripts": [
{
"js": ["src/content.js"],
"matches": ["https://www.google.com/*"]
}
]
}

Here we're telling Chrome to execute src/content.js on all pages that start with https://www.google.com.

Create the root element

Content scripts don't use an HTML file, so we need to create our root element and append it to the DOM before mounting our Vue app.

src/main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

const app = createApp(App)
// this element doesn't exist
app.mount('#app')

Let's add that root element. Make a copy of src/main.js and name it src/content.js. Add the highlighted code.

src/content.js
import { createApp } from 'vue'
import App from './App.vue'

const root = document.createElement('div')
root.id = 'crx-root'
document.body.append(root)

const app = createApp(App)
app.mount(root)

Get the right URL

info

Content scripts share the origin of the page where they run.

The browser treats the imported value logo as a URL from the host page. If the content script is running on https://google.com, the following img tag will try to load from https://google.com/src/assets/image.png.

src/App.vue
<script setup>
import logo from './assets/image.png';

</script>
<img
:src="logo"
className='App-logo'
alt='logo'
/>

We need to get a URL with our extension id for static assets like images. Use the getURL() method to get the extension url for our logo:

src/App.vue
<script setup>
import logo from './assets/image.png';
const logoUrl = chrome.runtime.getURL(logo);
</script>

<template>
<img :src="logoUrl" className='App-logo' alt='logo' />
</template>

Now our content script is ready for action! Let's try it out in the next section.