Replies: 1 comment 1 reply
-
This happens because Vite generates ES modules. A module only executes once, no matter how many times it is imported. CRXJS uses an import wrapper to inject content scripts; this means that when you re-execute a content script, it appears to do nothing. One way to work around this is by creating a mount function in the content script and sending a message from the background to execute it. // background.ts
import content from "./content?script";
const injectReactComponent = (tabId: number) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0].url?.includes("some/urls")) {
chrome.tabs.sendMessage(tabId, { type: "mountApp" })
}
});
}; // content.tsx
function mount() {
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
function mount() {
const titleElement = document.querySelector('.js-title-edit-button')
const root = document.createElement('div')
root.id = 'crx-root'
titleElement?.after(root)
ReactDOM.createRoot(root).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
}
// mount the app on load
mount()
// re-mount the app on each message
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'mountApp') {
mount()
}
}); Good luck with your Chrome Extension! |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am developing a Google Chrome extension that adds custom buttons on GitHub pull request pages, next to the edit button, like this:
I am using React and Vite to build my extension and it is working well on first render, but I am facing an issue when the page updates on certain events (like add comments to the PR, or update the PR description), my custom buttons disappear.
I think it's because of Github pages are now SPA and cause re-render of certain parts of the DOM.
To counter that, I have set up a system that listens to webRequests and when a webRequest seems to be associated with a specific event on the page, I trigger a function that injects my React code again.
I verified, my injection work well:
But I'm facing an issue here, when I inject my
content.tsx
file, nothing happens.But the funny thing here is that it works perfectly when I create another file, strictly identical to
content.tsx
and then, import it.Can anyone help me figure out how to re-inject my initial React code when an event occurs and causes a re-render of certain parts of the page?
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions