Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将chrome扩展限制为一个选项卡?_Javascript_Google Chrome_Tabs - Fatal编程技术网

Javascript 如何将chrome扩展限制为一个选项卡?

Javascript 如何将chrome扩展限制为一个选项卡?,javascript,google-chrome,tabs,Javascript,Google Chrome,Tabs,我有一个扩展,可以进行随机bing搜索 chrome.browserAction.onClicked.addListener(function(){ var a = Math.floor((Math.random()*100)+1); chrome.tabs.update(tabId,{'url': "http://www.bing.com/search?q=" + a}); var x = 0; var intervalID = setInterval(function(){

我有一个扩展,可以进行随机bing搜索

chrome.browserAction.onClicked.addListener(function(){   
var a = Math.floor((Math.random()*100)+1);
chrome.tabs.update(tabId,{'url': "http://www.bing.com/search?q=" + a});

var x = 0;
var intervalID = setInterval(function(){

    a = Math.floor((Math.random()*100)+1);
    chrome.tabs.update({'url': "http://www.bing.com/search?q=" + a});

    // how many times it should work 
    if(++x === 7){
        window.clearInterval(intervalID);
    }
},5000); // this is the delay, in milliseconds
})

问题是,这将在当前选项卡上执行搜索。因此,如果我切换选项卡或打开新窗口,它会在我当前的选项卡上进行搜索。我希望它在开始的选项卡上继续

我的解决方案是将tabId传入chrome.tabs.update。但是,我遇到的问题是,我不知道如何获取上一个选项卡的tab.id。我如何解决这个问题

谢谢你的帮助

--我尝试的修复:

var tabId;

chrome.tabs.query(
  {currentWindow: true, active : true},
  function(tabArray){
    tabId = tab.id;
  }
);

chrome.browserAction.onClicked.addListener(function(){   
var a = Math.floor((Math.random()*100)+1);
chrome.tabs.update(tabId,{'url': "http://www.bing.com/search?q=" + a});

var x = 0;
var intervalID = setInterval(function(){

    a = Math.floor((Math.random()*100)+1);
    chrome.tabs.update(tabId,{'url': "http://www.bing.com/search?q=" + a});

    // how many times it should work (after the first one initially
    if(++x === 3){
        window.clearInterval(intervalID);
    }
},5000); // this is the delay
})