Javascript 如何使js脚本只运行一次/有限的时间?

Javascript 如何使js脚本只运行一次/有限的时间?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,在chrome扩展中,我有执行以下操作的代码: -> User goes to website -> -> User sees a list of URLs to tables, they click one -> -> My script opens a new tab in response to scraping the table. 这很好,但是在我打开新选项卡的最后一步中,我希望我打开的选项卡在扩展生命周期中只打开一次。因此,当用户第一次单击表的UR

在chrome扩展中,我有执行以下操作的代码:

-> User goes to website -> 
-> User sees a list of URLs to tables, they click one -> 
-> My script opens a new tab in response to scraping the table.
这很好,但是在我打开新选项卡的最后一步中,我希望我打开的选项卡在扩展生命周期中只打开一次。因此,当用户第一次单击表的URL时,选项卡将为他们打开,然后再也不会打开。我怎样才能做到这一点

为清楚起见,并避免被否决,我只想运行一次这段代码

window.open(URL, '_blank')

只需在扩展脚本中使用布尔值

var done = true;
然后在用户单击url时执行检查:

if (!done) {
    //open tab
}
要存储该值,可以使用
localStorage

window.localStorage.setItem(“完成”,true);
然后,无论何时执行检查:

if(!window.localStorage.getItem(“完成”)){
//打开选项卡
}

但当您访问新站点时,变量是否会刷新?那么“完成”将被重置,不是吗?如果您想永久存储它,可以使用
localStorage
。我也要加上它。拥有一个本地存储阵列并添加到其中怎么样?然后你就可以
window.localStorage.setItem(“donarr”,[true,true,false,true])
我怀疑它会这么简单。我认为您应该首先获得整个数组,比如
var arr=window.localStorage.getItem(“donarr”)。然后按下变量
arr.push(true)。最后,将item设置为变量
window.localStorage.setItem(“donarr”,arr)。使用chrome.storage API。