Chrome tabs query returning empty tab array
Asked Answered
I

1

14

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>"]}
);
Itself answered 29/1, 2020 at 19:39 Comment(2)
@wOxxOm I have both open. I tried with all dev stuff closed and just the page the extension is supposed to run on and still I have a problem. After reloading, the extension still isn't communicating correctly. I think I have to restructure the scripts so the content script always initiates contact with the background.Itself
@wOxxOm I just added the sendToTab to the question.Itself
R
25

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...
  });
});
Remuneration answered 14/9, 2020 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.