我试图在我的铬扩展名中从背景脚本发送消息到内容脚本。但是看起来消息是在加载内容脚本之前发送的吗?
这是我在正常使用扩展时遇到的错误:
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
这是我的带有tabs.onUpdated
函数的后台脚本:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.url) {
console.log(changeInfo.url, tabId)
chrome.tabs.sendMessage(tabId, {
url: changeInfo.url,
type: 'URL_CHANGE'
});
}
});
这是我的内容脚本接收功能:
chrome.runtime.onMessage.addListener((obj, sender, response) => {
console.log('received', obj)
if (obj.type === 'URL_CHANGE') {
console.log('testestsetst')
getAuth()
getUrlType(obj.url)
} else if (obj.type === 'AUTH') {
getAuth()
} else if (obj.type === 'UN-AUTH') {
removeAuth()
}
});
每当我正常运行扩展时,我都不会看到我的内容脚本的输出,而且我得到了上面所述的错误。然而,当我调试后台脚本并逐步遍历代码时,我没有发现任何错误,并且我的内容脚本正确地打印了所有内容。这可能是因为需要加载的页面吗?如果是的话,我该如何解决这个问题?
发布于 2022-07-28 10:54:48
通过检查选项卡是否完成并通过tab参数发送url来解决这个问题,如下所示:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
chrome.tabs.sendMessage(tabId, {
url: tab.url,
type: 'URL_CHANGE'
});
}
});
发布于 2022-11-21 17:32:25
background.js
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason == "install") {
chrome.tabs.create({ url: chrome.runtime.getURL(`onboard-page.html`) }, function (tab) {
chrome.tabs.onUpdated.addListener(function listener(tabId, changeInfo) {
if (tabId === tab.id && changeInfo.status == 'complete') {
chrome.tabs.onUpdated.removeListener(listener)
// Now the tab is ready!
chrome.tabs.sendMessage(tab.id, "hello")
}
});
});
} else if (details.reason == "update") {
}
});
content-script.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
console.log(message)
});
https://stackoverflow.com/questions/73151563
复制相似问题