Piter Parker
Piter Parker

Reputation: 275

Obtain the tabId of new created tab

How do I get the tabId of a new created tab? My tabId I want to send in sendMessage is undefinded. How do I get the tabId?

Later I need the tabId to update the tabs....

popup.js

$(document).ready(function () {
    "use strict";
    $('button').on('click', function () {
      chrome.tabs.create({
          url: "http://google.de"
      }, function(tab) {
        });
        chrome.runtime.sendMessage({content: tabId, type:'urlDe'});
        window.close();
    });
      chrome.tabs.create({
          url: "http://google.com"
      }, function(tab) {
        });
        chrome.runtime.sendMessage({content: tabId, type:'urlCom'});
        window.close();
    });
});

background.js

chrome.runtime.onMessage.addListener(function(request) {
    if (request.type === 'urlDe') {
        alert(request.type + request.content);
    } else if (request.type === 'urlCom') {
        alert(request.type + request.content);
    }
});

Upvotes: 2

Views: 1678

Answers (1)

Sergii Rudenko
Sergii Rudenko

Reputation: 2684

You need to access to the tabId via tab.id in your callback function, because chrome.tabs.create is async function:

 chrome.tabs.create({
      url: "http://google.de"
  }, function(tab) {
     chrome.runtime.sendMessage({content: tab.id, type:'urlDe'});
  });
});

More information are in documentation or in this question.

Upvotes: 2

Related Questions