How send message from background to content script UI

My background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// read changeInfo data and do something with it (like read the url)
if (changeInfo.url) {
// console.log(changeInfo)
// do something here
chrome.tabs.sendMessage(tabId, { greet: "hello" })
}
})
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// read changeInfo data and do something with it (like read the url)
if (changeInfo.url) {
// console.log(changeInfo)
// do something here
chrome.tabs.sendMessage(tabId, { greet: "hello" })
}
})
And in the content/panel.js
useEffect(() => {
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log("Received %o from %o, frame", msg, sender.tab, sender.frameId)
})
}, [])
useEffect(() => {
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
console.log("Received %o from %o, frame", msg, sender.tab, sender.frameId)
})
}, [])
I think there is no issue with permission. I have given the permission below: "permissions": [ "tabs", "activeTab" ] After doing this the extension throws me an error.
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Context
static/background/index.js
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Context
static/background/index.js
Whats the problem with my code? Please explain if you know
No description
10 Replies
nithur
nithur•14mo ago
did you try taking the onmessage handler out of useeffect?
Asif
AsifOP•11mo ago
@louis can you help me with this?
matrix
matrix•11mo ago
does your content script run in the main world?
Asif
AsifOP•11mo ago
No
lab
lab•11mo ago
@Asif if you want to send data from bgsw to csui, you must do a handshake first via the port protocol. If you want to do it at onUpdated, the csui will not be available at that time. Generally, it's not advisable to send data from bgsw -> csui, since csui is considered short-lived and its life cycle is not owned by you.
Asif
AsifOP•11mo ago
Can you give me a simple code example of the current scenario?
lab
lab•11mo ago
It cannot be simple since the nature of what you're trying to do is complex :d...
Asif
AsifOP•11mo ago
Thanks. One more question. MAIN world is necessary to acheive pub/sub?
YAGPDB.xyz
YAGPDB.xyz•11mo ago
Gave +1 Rep to @louis (current: #1 - 166)
Want results from more Discord servers?
Add your server