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

本文标签: javascriptChrome Extension is failing to sendMessasge() from chromestorageonChange handlerStack Overflow