1

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);
    }
});
Piter Parker
  • 255
  • 1
  • 2
  • 13

1 Answers1

2

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.

Sergii Rudenko
  • 2,603
  • 1
  • 22
  • 24
  • Thanks, but the code in function(tab) { chrome.runtime.sendMessage({content: tab.id, type:'urlDe'}); }); never gets executed. If I put it outside the callback it will be executed, why? – Piter Parker Jan 05 '18 at 08:35
  • I think its why its in a popup, and when the new window gets opened, the code stops – Piter Parker Jan 05 '18 at 11:36