javascript - 如何选择当前选项卡右侧的所有选项卡?
问题描述
如果您右键单击 Chrome 浏览器顶部的任何选项卡,您将在右侧看到一个名为“关闭选项卡”的选项。这将关闭当前活动选项卡右侧的所有选项卡。我正在尝试使用 Chrome 扩展程序做类似的事情。可以使用诸如“当前活动选项卡的索引直到最后一个选项卡的索引”之类的循环来选择右侧的选项卡吗?
以下是开源 Chrome 扩展程序的源代码。该函数选择当前窗口中除活动选项卡外的所有选项卡并“暂停”它们。我正在尝试编写一个类似的函数,但不是所有选项卡,它只需要选择活动选项卡右侧的选项卡。
function suspendAllTabs(force) {
const forceLevel = force ? 1 : 2;
getCurrentlyActiveTab(activeTab => {
if (!activeTab) {
gsUtils.warning(
'background',
'Could not determine currently active window.'
);
return;
}
chrome.windows.get(activeTab.windowId, { populate: true }, curWindow => {
for (const tab of curWindow.tabs) {
if (!tab.active) {
gsTabSuspendManager.queueTabForSuspension(tab, forceLevel);
}
}
});
});
解决方案
每个选项卡都有一个index
显示其位置的选项卡。例如,第 3 个选项卡的索引为 2(从 0 开始)。
tab.index +1
因此,任何选项卡右侧的选项卡意味着tabs.length
例如...
将选项卡放在活动选项卡的右侧
// get all the tabs in current window
chrome.tabs.query({currentWindow: true}, tabs => {
let activeIndex;
for (const tab of tabs) {
// set the activeIndex so we wont have to run a loop on the tabs twice
if (tab.active) { activeIndex = tab.index; }
// tabs to the right of the active tab will have higher index
if(typeof activeIndex !== 'undefined' && tab.index > activeIndex) {
// tabs is on the right of the active tab ... do whatever needed
}
}
});
获取活动选项卡左侧的选项卡
// get all the tabs in current window
chrome.tabs.query({currentWindow: true}, tabs => {
for (const tab of tabs) {
// stop when reached the active tab
if (tab.active) { break; }
// tabs to the left of the active tab ... do whatever needed
}
});
推荐阅读
- javascript - React-Select - 处理多个选择和删除的更改
- node.js - 嗨,我正在尝试创建一个 Oauth2.0 令牌,以便我可以使用 nodejs 访问谷歌分析报告 api,但是我收到了无效的授权错误
- reactjs - 如何在 typescript 中连接 react-hook-form、react-select 和 yup?
- pandas - 前 10 名 ODI 玩家的网页抓取
- typescript - 如何批量删除 Discord 机器人
- java - Spring boot MongoRepository - 在 Mongodb 中存储 JSON
- lua - lua (love2d): 函数应该没有结束
- opencv - Openpose 演示在 Ubuntu20.04 中使用 coredump 完成
- websocket - LetsEncrypt Sep 30 到期后,Goaccess Web 套接字在 Safari 上失败
- html - 如何对齐列中的图标、数字和文本?