简体   繁体   中英

chrome.tabs.create function wrapper, why doesn this work?

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?

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM