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,
0 Replies