admin管理员组文章数量:1122832
I am developing a Chrome V3 extension with an options page that uses chrome.storage to persist user prefs.
On the background script js I have a listener that handles chrome.storage updates by firing sendMessage to the content script and awaiting confirmation back. The goal is to immediately fire scripts from the content script as soon as user preferences are updated, but sendMessage appears to not be firing.
The code I'm using is below:
// background.js
chrome.storage.onChanged.addListener( async ( changes, namespace ) => {
const queryOptions = { active: true, lastFocusedWindow: true }
const [ tab ] = await chrome.tabs.query( queryOptions )
for ( const [ key, { newValue } ] of Object.entries( changes ) ) {
const message = JSON.parse( `{ "${ key }":${ newValue }}` )
chrome.tabs.sendMessage( tab.id, { message }, function ( response ) {
if ( !chrome.runtime.lastError ) {
if ( typeof response !== 'undefined' ) {
console.log( { response } )
}
}
} )
}
} )
// content.js
chrome.runtime.onMessage.addListener( function ( message, sender, sendResponse ) {
console.log( { message } )
const response = 'got it'
sendResponse( { response } )
} )
Since I'm using an options page instead of embedded options UI, the chrome.tabs API is available, however, I misread the docs and initially used chrome.runtime.sendMessage. Still, I'm able to capture the tab that I want from the background script, ie. I'm able to get an object representing the active tab that contains id keys for tab and window.
Additionally I've commented out all code except for what's needed for messaging, but still the same results.
I've previously designed an extension that sends messages between background and content scripts that uses nearly this same code but something seems to be preventing that in this case.
I'm mostly certain that it can't be code from the site my extension's acting on that's preventing sendMessage but cannot be certain
版权声明:本文标题:javascript - Chrome Extension is failing to sendMessasge() from chrome.storage.onChange handler - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736283428a1926965.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论