Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome tabs query returning empty tab array

I'm trying to port a Web Extension that I've gotten working in Firefox to chrome and I having some problems. I need to send a message form the background script to a content script. I was using a port when I first build it from Firefox, but I switched it to using chrome.tabs.query() because chrome kept finding an error. But now with query(), it still works fine in Firefox, but now chrome is saying that it can't find the current tab:

Error handling response: TypeError: Cannot read property 'id' of undefined
    at chrome-extension://hhfioopideeaaehgbpehkmjjhghmaaha/DubedAniDL_background.js:169:11

It returns that the tab argument pass is length == 0. console.log(tabs):

[]

This is the function that Chrome is complaining about.


var browser = chrome; // I set this only for compatibility with chrome; not set in Firefox.

function sendToTab(thing) {
    browser.tabs.query(
    {active: true, currentWindow: true},
    function(tabs) {
        console.log(tabs);
        browser.tabs.sendMessage(
            tabs[0].id, // The inspector identifies an error on this line
            thing
        );
    }
    );
}

The same function works fine in Firefox and has no problem getting access to the tab. But it doesn't work in Chrome.

Update 2020-01-30

@wOxxOm:

Show the code that calls sendToTab

This is where sendToTab is called:

function logURL(requestDetails) {
    var l = requestDetails.url;
    if (l.includes(test_url)) {
        if (logOn) { console.log(l); }
        sendToTab({dl_url: l});
    }
}


browser.webRequest.onBeforeRequest.addListener(
    logURL,
    {urls: ["<all_urls>"]}
);
like image 822
9716278 Avatar asked Jan 29 '20 19:01

9716278


1 Answers

Sounds like you're running this code while your active window is devtools, which is a known bug.

Another problem takes place in your code: it always accesses the focused (active) tab even though the request may have occurred in a backgrounded (inactive) tab.

Solution:

Use the tab id provided inside the listener function parameter as tabId property.
In your case it's requestDetails.tabId

If for whatever reason you really want the active tab, make sure a real window is active while this code runs or use the following workaround that succeeds even if devtools window is focused:

chrome.windows.getCurrent(w => {
  chrome.tabs.query({active: true, windowId: w.id}, tabs => {
    const tabId = tabs[0].id;
    // use tabId here...
  });
});
like image 190
wOxxOm Avatar answered Oct 12 '22 11:10

wOxxOm