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

只谈情不闲聊 提交于 2019-12-25 03:59:22

问题


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



来源:https://stackoverflow.com/questions/8302218/chrome-tabs-create-function-wrapper-why-doesn-this-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!