Error on sending message from background script to content script

Hello everyone, I am trying to send a message from background script to content script but it's not working. Every time I am trying to do that I am getting an error => Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist. Background code => import { getPort } from "@plasmohq/messaging/port" // Listen for tab updates to ensure content script is loaded chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { // Check if the URL matches where our content script runs if ( changeInfo.status === "complete" && tab.url && (tab.url.includes("gemini.google.com") || tab.url.includes("chatgpt.com")) ) { const port = getPort("TestPort") setTimeout(() => { // Send test message port.postMessage({ type: "background-message", data: "Hello from background! Tab is ready." }) }, 6000) } }) Port => import type { PlasmoMessaging } from "@plasmohq/messaging" const handler: PlasmoMessaging.PortHandler = async (req, res) => { const { name, body } = req // Handle incoming messages if (name === "TestPort") { // Process the message and send response res.send({ success: true, message: "Message received", data: body }) } } export default handler Content Script => const PlasmoOverlay = () => { const [lastMessage, setLastMessage] = useState("") const port = usePort("TestPort") useEffect(() => { port.listen( (msg) => { console.log('msg object ', msg); }) }, []) return ( <div style={{ padding: "20px", background: "#f5f5f5", margin: "10px" }}> <h1>Messages from Background</h1> {lastMessage && ( <div> <strong>Last received message:</strong> <pre>{lastMessage}</pre> </div> )} </div> ) } export default PlasmoOverlay but it's not working,
2 Replies
vunsh
vunsh•4mo ago
@rejoan im not sure if ur stil experiencing this issue but i was abel to fix it with adjusting my package.json:
"plasmo": {
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content.ts"
],
"run_at": "document_idle" //added this line
}
]
"plasmo": {
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content.ts"
],
"run_at": "document_idle" //added this line
}
]
Mohd Rejoan
Mohd RejoanOP•4mo ago
That item is added by default. I will do my best to create a demo Git repository and share it with you.

Did you find this page helpful?