我正在寻找一种通过代码在网页上改变选项卡的方法(即跳转到下一个打开的选项卡,这与按住CTRL键并按TAB键相同)。我希望能够在页面上任何地方单击,即可跳转到下一个选项卡。我了解点击网页部分,只是不知道如何访问Chrome选项卡。
这是否可能实现?
谢谢,
这是否可能实现?
谢谢,
可以和不可以。
如果您的意思是在网站内使用JavaScript前往下一个标签页:如果您没有通过window.open
打开其他标签页(例如尝试前往未直接从当前网站打开的另一个标签页),那么不能,这是不可能的。如果可能的话,将会是一种安全风险并为攻击者提供另一种“ID”用户或潜在查找获得关于用户打开的其他标签页信息的方式。
如果您在网站内打开了标签页,则可以使用focus方法聚焦到它们。
var newTabs = [];
newTabs.push( window.open("https://example.com", "_blank") );
// Add more tabs?
// Sorry, no way to figure out what the "next" tab is in the
// browser's list of tabs via straight on-site JavaScript,
// just go by next index in the array...
newTabs[0].focus();
如果您指的是您正在开发的Chrome浏览器扩展程序,那么是的,您可以使用Tabs API在扩展中前进到下一个选项卡。注意:我没有测试过这个功能,但它似乎符合我看到的文档和示例。如果您尝试并找到更好的解决方案,请告诉我,我会进行更新。// Query current active tab in the current active window:
chrome.tabs.query({currentWindow: true, active: true}, function(tabsArray) {
// If there are fewer than 2 tabs, you are on the only tab available.
// Nothing left to do.
if( tabsArray.length < 2 ) return;
// Else query tab with incremented index (e.g. next tab):
chrome.tabs.query({index: (tabsArray[0].index+1)}, function(nextTabsArray){
// There is no next tab (only 1 tab or user is on last tab)
if( nextTabsArray.length < 1 ) return;
// Else, yay! There is a next tab, lets go!
chrome.tabs.update(nextTabsArray[0].id, {active: true})
});
});
chrome.tabs.query({ currentWindow: true }, (tabsArray) => {
// If only 1 tab is present, do nothing.
if (tabsArray.length === 1) return;
// Otherwise switch to the next available tab.
// Find index of the currently active tab.
let activeTabIndex = null;
tabsArray.forEach((tab, index) => {
if (tab.active === true) {
activeTabIndex = index;
}
});
// Obtain the next tab. If the current active
// tab is the last tab, the next tab should be
// the first tab.
const nextTab = tabsArray[(activeTabIndex + 1) % tabsArray.length];
// Switch to the next tab.
chrome.tabs.update(nextTab.id, { active: true });
});
如果您知道窗口名称(通常是如果您创建了该窗口),并且您在同一域中,您可以使用调用window.open
时的窗口名称部分切换到该窗口。
const myTab = window.open('https://stackexchange.com/questions', 'questions') // first call opens it
myTab.name = 'tags' // renaming window is fine
window.open('https://stackexchange.com/tags', 'tags') // second call switches to it
窗口将重新加载,请记住这一点。
如果您可以访问要切换的选项卡,理论上您可以使用postMessages执行以下操作:
// assuming you have this set up:
// https://dev59.com/DlsX5IYBdhLWcg3wU-JM
// in the tab for https://same.domain/page-one
Window.name = 'new name'; // set current window name
sendMessage('new name') // using the linked code
// switch to the other tab, e.g. https://same.domain/page-two
// In your message event listener
function receiveMessage(e){
window.SiblingName = e.data;
}
window.open('https://same.domain/page-one', window.SiblingName)
虽然我还没有让上述内容正常工作。