chrome.tabs.query callback not working with chrome.storage.local.get callback

354 views
Skip to first unread message

Jacob Kim

unread,
May 4, 2022, 2:38:38 AM5/4/22
to Chromium Extensions
Hi. I have made an chrome extension and building extensions is really cool. 

While I am debugging messaging between contents.js and background.js in my extension, I found this not working

//background.js

chrome.runtime.onMessage.addListener((msg) => {

    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
      chrome.storage.local.get(['msg'], function(res){
////// on this line, tabs returns empty array [] but it should returns array with tabs ////////
      console.log(tabs);
      })
    })
)}

And I fixed by just changing two lines 


//background.js

chrome.runtime.onMessage.addListener((msg) => {

////// just switched lines this 
    chrome.storage.local.get(['msg'], function(res){
////// and this
      chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
////// this returns array with tabs onject successfully ////////
      console.log(tabs);
      })
    })
)}

I thought `chrome.storage.local.get`'s callback function should takes tabs argument from `chrome.tabs.query` but it isn't. Why this not working? Any comments will be thankful. 

wOxxOm

unread,
May 4, 2022, 10:22:08 AM5/4/22
to Chromium Extensions, jacobk...@gmail.com
There's no such difference, so what you are observing is caused by something else. A common reason is having an undocked devtools window currently focused.

BTW instead of chrome.tabs.query you should probably use the tab which sent the message as it may be inactive (i.e. in background):

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  console.log(msg, sender.tab);
});

Reply all
Reply to author
Forward
0 new messages