现在无法查询选项卡(用户可能正在拖动选项卡)

Nic*_*las 8 javascript google-chrome google-chrome-extension

我有一个 chrome 扩展,可以通过以下代码访问活动选项卡:

    chrome.tabs.query({ active: true }, (result) => { ... })
Run Code Online (Sandbox Code Playgroud)

在最近的更新之前,这一直运行良好,我无法再查询选项卡,控制台中打印了以下错误:

Tabs cannot be queried right now (user may be dragging a tab).
Run Code Online (Sandbox Code Playgroud)

我试过这个,但它不起作用。有什么建议?

小智 1

我相信您已经使用清单 v2 构建了扩展。尝试通过chrome.runtime.lastError避免此错误。如果您在代码中使用了chrome.tabs.onUpdated.addListener(...)或其他侦听器方法,请按如下所示更新它,这样就不会抛出此错误。

chrome.tabs.onUpdated.addListener( (tabId, statusInfo, tabInfo) => {
   //this will prevent it from throwing the error
   if (chrome.runtime.lastError) {}
   //rest of your code 
})
Run Code Online (Sandbox Code Playgroud)

如果您使用chrome.tabs.query({ active: true }, (result) => { ... }) ,也可以在代码其余部分或chrome.tabs.onUpdated.addListener(...)侦听器内的任何位置然后也更新它,如下所示:

chrome.tabs.query({active: true}, result => {
   //this will prevent it from throwing the error
   if (chrome.runtime.lastError) {}
   //rest of your code 
})
Run Code Online (Sandbox Code Playgroud)