0

I'm making a simple chrome extension and need to have my popup page connect to the content script on the current tab. However it keeps giving me an error for the tabId argument to tabs.connect. It's saying the tab id I'm passing is undefined rather than an integer. I have no idea why.

Full Error:

Uncaught Error: Invocation of form tabs.connect(undefined, object) doesn't match definition tabs.connect(integer tabId, optional object connectInfo)
    at Object.normalizeArgumentsAndValidate (extensions::schemaUtils:115)
    at Object.<anonymous> (extensions::binding:363)
    at connectToCurrentTab (popup.js:21)
    at HTMLDocument.<anonymous> (popup.js:44)
    at mightThrow (jquery-3.2.1.js:3583)
    at process (jquery-3.2.1.js:3651)

I made a short function to retrieve the current tab id:

function getCurrentTabId() {
    var query = {active: true, currentWindow: true};

    var tabId;

    chrome.tabs.query(query, function (tabArray) {
        tabId = tabArray[0].id;

        console.log("Tab id: " + tabId);
    });

    return tabId;
}

It appears to be getting the correct tab id or at least an integer. Console out put: Tab id: 111

I use the current tab id retrieved by getCurrentTabId to chrome.tabs.connect from my popup to the content script running on the current tab then return the Port it connected on.

function connectToCurrentTab () {
    var currentTabId = getCurrentTabId();

    return chrome.tabs.connect(currentTabId, {name: "popup"}); //<-- error thrown here
}

Any help or information is much appreciated.

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Daniel Herr Jan 04 '18 at 22:59

1 Answers1

1

Your code is almost correct, the problem it's than chrome.tabs.query is async method. So, at the moment when you call chrome.tabs.connect - currentTabId it's undefined.

You can fix it with usage of callback function:

function getCurrentTabId(cb) {
    var query = {active: true, currentWindow: true};
    chrome.tabs.query(query, function (tabArray) {
        console.log("Tab id: " + tabArray[0].id);
        cb(tabArray[0].id)
    });
}

function connectToCurrentTab () {
    getCurrentTabId(function(currentTabId) {
       chrome.tabs.connect(currentTabId, {name: "popup"})
    });
}

You can also use a Promise to prevent a callbacks hell.

Sergii Rudenko
  • 2,603
  • 1
  • 22
  • 24
  • Fixed my problem. Much appreciated sir! Must have missed the part about it being asynchronous in the documentation. Been programming ever since I can remember and still making rookie mistakes. :P Oh well, happens to all of us. – Edward Severinsen Jan 04 '18 at 06:09