我正在尝试构建一个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;
}
}
});
}
更新
根据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"
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句