DEV Community

Discussion on: Real Vite-React HMR in Chrome Extension Content Scripts

Collapse
 
moinulmoin profile image
Moinul Moin

Great!

how to work with background.js for service worker? you should include it in the doc

Collapse
 
jacksteamdev profile image
Jack Steam

Great idea! We're working on the docs, you can take peek here: crxjs.dev/vite-plugin

Check out this comment for instructions on the background service worker: dev.to/lichenglu/comment/1od4p

Collapse
 
moinulmoin profile image
Moinul Moin

I checked, I did the same in maniest json. this code will work fine inside it?

Thread Thread
 
moinulmoin profile image
Moinul Moin
// path: src/background/index.js

console.log('I am background.js');

chrome.action.onClicked.addListener((tab) => {
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ['src/main.jsx'],
    });
});

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
moinulmoin profile image
Moinul Moin

I am actuallyy trying to inject the content script by clicking on the icon of extension. so, kindly tell me how it will work, I tried with this code. but It throw error at this line

files: ['src/main.jsx'],
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
jacksteamdev profile image
Jack Steam

You can import the script with a script query:

// note how the import path ends with `?script`
import scriptPath from './content-script?script'

chrome.action.onClicked.addListener((tab) => {  
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: [scriptPath]
  });
});
Enter fullscreen mode Exit fullscreen mode

This will also provide HMR for the imported script. More info: Dynamic content scripts