我正在尝试构建一个Chrome扩展程序,它会将当前标签左侧的所有标签移动到新窗口。
当我执行以下代码时,它会在每个左侧选项卡中移动它自己的窗口。因此,如果当前选项卡左侧有2个选项卡,它将创建2个窗口,每个窗口中有1个选项卡。如何获取它以便它只将所有左侧选项卡移动到一个新窗口(即:它不会为当前选项卡左侧的每个选项卡创建一个新窗口)?
function groupTabsToTheLeft(info, tab) {
chrome.tabs.getAllInWindow(null, function (tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].index < tab.index) {
chrome.windows.create({"tabId": tabs[i].id});
} else {
break;
}
}
});
}
答案 0 :(得分:3)
<强>更新强>
根据OP的额外要求,以下解决方案具有以下规格:
你可以这样做:
示例 background.js 将如下所示:
chrome.browserAction.onClicked.addListener(function(tab) {
/* Get the `tab`'s window along with its containing tabs */
chrome.windows.get(tab.windowId, { populate: true }, function(oldWin) {
/* Determine which tabs should be moved
* (i.e. are on the left of `tab` */
var tabs = oldWin.tabs;
var tabsToMove = [];
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].index < tab.index) {
tabsToMove.push(tabs[i].id);
}
}
/* If there are any tabs to move... */
if (tabsToMove.length > 0) {
/* Create a new window with the same
* location and size as the original */
chrome.windows.create({
top: oldWin.top,
left: oldWin.left,
width: oldWin.width,
height: oldWin.height,
focused: false
}, function(newWin) {
/* Remove the new, empty tab created by default */
chrome.tabs.query({
windowId: newWin.id
}, function(tabsToClose) {
/* Update the window's state (e.g. "maximized") */
chrome.windows.update(newWin.id, { state: oldWin.state });
/* Move the tabs to the newly created window */
chrome.tabs.move(tabsToMove, {
windowId: newWin.id,
index: -1
}, function() {
/* Close any tabs that pre-existed (i.e. 1 empty tab)
* [Do not do this BEFORE moving the tabs,
* or the window will be empty and will close] */
var lastIdx = tabsToClose.length - 1;
tabsToClose.forEach(function(t, idx) {
chrome.tabs.remove(t.id);
if (idx === lastIdx) {
chrome.windows.update(oldWin.id, {
focused: true
});
}
});
});
});
});
}
});
});
为了完整起见,随附的 manifest.js 可能如下所示:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": true,
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"browser_action": {
"default_title": "Test Extension"
//"default_icon": {
// "19": "img/icon19.png",
// "38": "img/icon38.png"
//},
},
"permissions": [
"tabs"
]
}
答案 1 :(得分:0)
if (tabs[i].index < tab.index) {
**chrome.windows.create**({"tabId": tabs[i].id});
} else {
break;
}
如果您创建新窗口,每次进入时都会遇到问题。 因此,您只需为第一个选项卡创建一个新窗口,并且必须为创建的窗口添加其他选项卡。