Q:

chrome extension correct implementation of two asynchronous function

hope to be fine
im not perfect in javascript and i have a question with two asynchronous function in developing a chrome extension.
well ; i want to implement functionality in a chrome extenstion which is when a user clicked on a button a new tab should be created and when the page is completely loaded i need to send message to the content script of that page.
the problem is in the create tab function of chrome extension , information of the new created tab will be sent in the callback function and i cannot save that tab id in global variable on the other hand for understanding when the page is completely loaded there is a listener which will listen on the status of the tabs again information of these tabs will be sent in the callback i dont know how to relate these two function together because i cannot save the information of tab id in global variable.
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if (info.status === 'complete') {
        chrome.tabs.sendMessage(tab.id, msg);
    }
});

chrome.tabs.create({ url: someurl , active: false },function(tab){

});

again thank you guys.
i appreciate any help because really i get confused and read many articles and  tried a lot of ways but no success.

A:

You can try chaining the asynchronous callbacks like:
//first create the tab
chrome.tabs.create({url: someurl, active:false}, function(tab){
    //once the tab is created, inject the content script
    chrome.tabs.executeScript(tab.id, {file:'yourContentScript.js'}, function(result){
        //as per default, the content script will run AFTER the page has loaded
        //once the content script has run and set up the listener, send the message
        chrome.tabs.sendMessage(tab.id, {message:'hello, content script'});
    });
});

or you can use a global variable, assuming you have set "runAt":"document_idle" for your content script in your manifest:
var myTabId;

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (info.status === 'complete' && tabId == myTabId) {
        chrome.tabs.sendMessage(tabId, msg);
    }
});

chrome.tabs.create({ url: someurl , active: false },function(tab){
    myTabId = tab.id;
});

