chrome.tabs.create函数包装器,为什么不能正常工作? [英] chrome.tabs.create function wrapper, why doesn this work?

查看:129
本文介绍了chrome.tabs.create函数包装器,为什么不能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



<$>



<$>我有最新的Chrome,我正在建立一个扩展。 p $ p> var returnTab = false; //将变量初始化为false

var createNewTab = function(){
returnTab = false; //确保我们以这个var开头为false

chrome.tabs.create({url:'http://www.google.com/'},function(tab){
returnTab = tab; //将returntab对象放入变量
});

while(returntab === false){}; //等待标签被创建。
返回returnTab;
};
c = createNewTab();

一切都好,它应该可以工作;除非没有。 createNewTab()函数陷入无限循环,而变量returnTab永远不会获得回调返回值。
如果按照我的意思去做,没有等待循环,一切正常,回调函数按照它的方式执行。



为什么是不是有效?



LE:看起来回调函数等待循环完成。有没有人知道一种方法来保持整个函数繁忙,直到回调函数启动?

只是在这里猜测,因为我有没有制作Chrome扩展程序的实际经验,但也许while()循环占用线程,并且从不真正允许您在调用create()时指定的回调永远运行。这就是如果你在一个普通的网站上这样做的话。



尝试向等待循环添加setTimeout()调用,以便在等待时,不使用任何CPU,而是使用任何CPU ......我不确定如何在扩展的上下文中执行此操作,所显示的代码没有足够的上下文。



然而,如果我这样做了,而不是循环和等待,那么只需在回调函数中创建标签后添加想要执行的任何操作(正确设置returnTab的位置) 。这是在JS做东西的正常方式......


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

这篇关于chrome.tabs.create函数包装器,为什么不能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆