Chrome扩展程序-找出扩展程序选项卡是否打开 [英] Chrome Extension - Find out if extension tab is open

查看:95
本文介绍了Chrome扩展程序-找出扩展程序选项卡是否打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已设置为单击extn图标时-我的extn index.html打开.
如果我第二次单击该图标-我不希望它打开第二个选项卡.我希望它聚焦已打开的选项卡(如果已打开).

I have set up that when I click extn icon - my extn index.html opens.
If I click the icon a second time - I don't want it to open a second tab; I want it to focus the already open tab (if it's open).

问题出在if it's open部分.理想情况下,我不想请求tabs许可,因为它很麻烦.由于此限制,我无法迭代所有打开的选项卡并检查其URL.
我尝试将extn选项卡ID存储在chrome.local.storage中,并在单击extn按钮时检查它-但是始终保持最新的选项卡号被证明是相当困难的.最终的障碍是,当Chrome关闭时-它不会触发任何类型的onClose事件;因此,我无法清除现在过时的extn标签ID的本地存储.
因此,当我重新打开Chrome时,请点击extn按钮-它不会打开新标签页,因为它可以看到存储中的旧标签页ID,并认为该标签页已打开.

The problem is with if it's open part. Ideally, I would not want to ask for a tabs permission, as it is very intrusive. Because of this restriction I cannot iterate all the open tabs and check their urls.
I tried storing extn tab id in chrome.local.storage and checking for it when I click the extn button - but always maintaining up-to-date tab number proved to be rather difficult. The ultimate obstacle was that when Chrome is closed - it doesnt fire any type of onClose event; thus I cannot clear local storage of now obsolete extn tab id.
So, when I reopen Chrome, click extn button - it will not open the new tab because it can see the old tab id in the storage and thinks that a tab is already open.

有没有获得tabs许可的结果?

Is there any way to achieve the result w\o the tabs permission?

推荐答案

对于chrome://extensions UI中显示的嵌入式选项,您只需使用 chrome.runtime. openOptionsPage(),它将负责重新调整现有标签的位置.

For embedded options shown in chrome://extensions UI you can simply use chrome.runtime.openOptionsPage() which will take care of refocusing the existing tab.

要查找自己的扩展程序的独立标签,请使用 chrome.extension.getViews() chrome.tabs.getCurrent()在另一方调用标签的JS window以获得其自己的当前"标签:

To find a standalone tab of your own extension use chrome.extension.getViews() and chrome.tabs.getCurrent() invoked on the other tab's JS window to get its own "current" tab:

function getOwnTabs() {
  return Promise.all(
    chrome.extension.getViews({type: 'tab'})
      .map(view =>
        new Promise(resolve =>
          view.chrome.tabs.getCurrent(tab =>
            resolve(Object.assign(tab, {url: view.location.href}))))));
}

async function openOptions(url) {
  const ownTabs = await getOwnTabs();
  const tab = ownTabs.find(tab => tab.url.includes(url));
  if (tab) {
    chrome.tabs.update(tab.id, {active: true});
  } else {
    chrome.tabs.create({url});
  }
}

用法:

openOptions('index.html')

这篇关于Chrome扩展程序-找出扩展程序选项卡是否打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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