谷歌浏览器插件教程官方例子之管理标签页

Manage tabs 管理标签页

建立您的第一个选项卡管理器。

manifest.json

{
  "manifest_version": 3,
  "name": "Tab Manager for Chrome Dev Docs",
  "version": "1.0",
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  },
     "action": {
    "default_popup": "popup.html"
  },
    //限定这个域名下的页面有效果
    "host_permissions": [
    "https://developer.chrome.com/*"
  ],
     "permissions": [
    "tabGroups"
  ]
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./css/popup.css" />
</head>
<body>
<template id="li_template">
    <li>
        <a>
            <h3 class="title">Tab Title</h3>
            <p class="pathname">Tab Pathname</p>
        </a>
    </li>
</template>

<h1>Google Dev Docs</h1>
<button>Group Tabs</button>
<ul></ul>

<script src="./popup.js" type="module"></script>
</body>
</html>

popup.js

const tabs = await chrome.tabs.query({
    url: [
        "https://developer.chrome.com/docs/webstore/*",
        "https://developer.chrome.com/docs/extensions/*",
    ],
});
console.log('tabs',tabs)
const collator = new Intl.Collator();
tabs.sort((a, b) => collator.compare(a.title, b.title));

const template = document.getElementById("li_template");
const elements = new Set();
for (const tab of tabs) {
    const element = template.content.firstElementChild.cloneNode(true);

    const title = tab.title.split("-")[0].trim();
    const pathname = new URL(tab.url).pathname.slice("/docs".length);

    element.querySelector(".title").textContent = title;
    element.querySelector(".pathname").textContent = pathname;
    element.querySelector("a").addEventListener("click", async () => {
        // need to focus window as well as the active tab
        await chrome.tabs.update(tab.id, { active: true });
        await chrome.windows.update(tab.windowId, { focused: true });
    });

    elements.add(element);
}
document.querySelector("ul").append(...elements);

const button = document.querySelector("button");
button.addEventListener("click", async () => {
    const tabIds = tabs.map(({ id }) => id);
    const group = await chrome.tabs.group({ tabIds });
    await chrome.tabGroups.update(group, { title: "DOCS" });
});

chrome.tabs.update(tab.id, { active: true }); 更新标签也为选中

chrome.windows.update(tab.windowId, { focused: true });

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。
哪吒

哪吒 · 中级学士

热爱技术,喜欢新东西。

老程序员年度分享MVP
查看更多

最新视频课程