提问人:Ross Moody 提问时间:10/28/2023 更新时间:10/28/2023 访问量:24
Chrome 扩展程序 sendMessage “无法建立连接”错误与 Vite
Chrome extension sendMessage "could not establish connection" error with Vite
问:
我正在构建一个 Chrome 扩展程序,该扩展程序可以启动一个新选项卡并向该选项卡发送一条包含数据的消息。
当我使用rollup构建应用程序的生产版本时,有一个静态索引.html文件,扩展工作正常。
在开发模式下,Vite 不会生成静态 HTML 文件,因此当扩展在新选项卡中提供时,我认为存在某种竞赛,除非我将其放入 micro setTimeout,否则消息不会成功。
有什么想法如何让扩展在开发模式下正常运行吗?我现在正在通过在每次更改时将扩展构建为监视模式下的生产来解决这个问题,但据我所知,它有点违背了 Vite 的目的。
确切的错误是Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
export function launchSvgGobbler() {
chrome.action.onClicked.addListener(async ({ url }) => {
try {
// Create a new tab and send the data to the content script
const tab = await utils.createNewTab()
const sendMessage = () => chrome.tabs.sendMessage(tab.id!, { data: 'data' })
// Vite HMR issue. The page is loaded not statically, so we need to wait
// Production build works fine because static HTML is loaded.
if (process.env.NODE_ENV === 'development') {
setTimeout(sendMessage, 50)
} else {
sendMessage()
}
} catch (error) {
console.log('Error launching', error)
}
})
}
这是 createTab 函数。它工作正常,但在这里供参考:
/**
* Awaits the loading of a newly created tab and return the tab config.
* @param url The url to open relative to the extension. Defaults to index.html.
*/
export function createNewTab(url = 'index.html'): Promise<chrome.tabs.Tab> {
return new Promise((resolve) => {
chrome.tabs.create({ url, active: true }, (tab) => {
const listener = (updatedTabId, changeInfo, updatedTab) => {
if (
tab.id &&
updatedTabId === tab.id &&
changeInfo.status === 'complete' &&
updatedTab.status === 'complete'
) {
chrome.tabs.onUpdated.removeListener(listener)
resolve(updatedTab)
}
}
chrome.tabs.onUpdated.addListener(listener)
})
})
}
``
答: 暂无答案
评论
sender.tab?.id