chrome.tabs.create function wrapper, why doesn thi

2019-08-16 12:19发布

问题:

I have the latest Chrome, I'm building an extension.

Consider the following code:

var returnTab = false; // init the variable as false

var createNewTab = function(){
returnTab = false; // make sure we start with this var as false

chrome.tabs.create({url:'http://www.google.com/'}, function(tab){
    returnTab = tab; // put the returntab object inside the variable
});

while(returntab===false){  }; // wait for the tab to be created.
return returnTab;
};
c = createNewTab();

All fine and it should work; except it doesn't. The createNewTab() function gets stuck into an infinite loop and the variable returnTab never gets the callback return value. If I do it the way I'm meant to do it, without the wait loop everything works and the callback function executes the way it should.

Why isn't this working?

LE: Looks like the callback function waits for the loop to complete. Does anyone know a way to keep the whole function busy until the callback function fires up?

回答1:

Just guessing here, as I have no actual experience making Chrome extensions, but maybe the while() loop is hogging the thread and never really allowing the callback you specified in the call to create() to ever run. That's what would happen if you did this in a regular website.

Try adding a setTimeout() call to the waiting loop, so that, while it waits, it doesn't use any CPU, instead of using 100% of it... I'm not sure how you can do this in the context of your extension, the code you showed doesn't quite have enough context.

If I were doing this, however, instead of looping and waiting, i'd just add whatever you want to do once the tab is created in the callback function (right where you are setting returnTab). That's the normal way of doing stuff in JS...