Jon
Jon

Reputation: 29

Variable not being updated in Javascript

Here is the code:

var newTab;
chrome.tabs.create({url: (newUrl)}, function(tab){
  newTab = tab.id;
});
check();
alert(newTab);
chrome.tabs.update(newTab, {pinned: true});
chrome.tabs.update(tabid, {active: true});
chrome.tabs.remove(newTab);

The final instruction doesn't work. the newTab variable doesn't update so that is can be pinned and then remove.

Upvotes: 0

Views: 106

Answers (1)

Ben Aston
Ben Aston

Reputation: 55769

Try:

var newTab;
chrome.tabs.create({url: (newUrl)}, function(tab){
  newTab = tab.id;

  check();
  alert(newTab);
  chrome.tabs.update(newTab, {pinned: true});
  chrome.tabs.update(tabid, {active: true});
  chrome.tabs.remove(newTab);
});

// Code here is run before the tab is created.

The reason for this is that the create method on the tabs object is asynchronous. This means that any code after the method invocation will be run before the new tab has been created, causing the error.

Upvotes: 2

Related Questions