Dyl*_*eck 6 html javascript google-chrome
我正在寻找一种通过网页上的代码更改选项卡的方法(进入下一个打开的选项卡,这本质上就像按住 CTRL 并按 TAB 键一样)。我希望能够单击页面上的任意位置,然后它会转到下一个选项卡?我了解点击网页部分,而不是如何访问 chrome 标签。
这甚至可能吗?
谢谢,
Jim*_*Jim 10
是和否。
如果您的意思是可以在网站内使用 JavaScript 前进到下一个选项卡:如果您没有通过以下方式打开其他选项卡window.open(例如,尝试前进到不是直接从当前网站打开的另一个选项卡),那么不,它不是可能的。如果可能的话,这将是一个安全风险,并为攻击者提供另一个向量来“识别”用户或可能找到一种方法来访问有关用户已打开的其他选项卡的信息。
如果您确实打开了网站中的选项卡,则可以关注它们:
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();
Run Code Online (Sandbox Code Playgroud)
如果您指的是您正在使用的 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})
});
});
Run Code Online (Sandbox Code Playgroud)
正如 @jim 所说,不可能使用 JavaScript 在网站内切换选项卡。但可以使用Chrome 扩展中使用的Chrome 扩展选项卡 API来完成。
下面是我正在开发的扩展程序的代码片段。触发时它将切换到下一个选项卡:
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 });
});
Run Code Online (Sandbox Code Playgroud)
我希望这能解决您的疑问。如果您有更好的建议请告诉我。