简体   繁体   English

如何以编程方式使选项卡成为活动选项卡?

[英]How to programmatically make a tab become the active tab?

I am using BroadcastChannel to remotely control the contents shown in another browser window (on the same PC) displayed on a projector.我正在使用BroadcastChannel远程控制投影仪上显示的另一个浏览器 window(在同一台 PC 上)中显示的内容。 (Basically, the projected window is an extended desktop display.) It has worked nicely so far on both Chrome and Edge, with a short JS script each in the remote controlling page and the controlled page. (基本上,投影的 window 是一个扩展的桌面显示器。)到目前为止,它在 Chrome 和 Edge 上运行良好,在远程控制页面和受控页面中各有一个简短的 JS 脚本。

However, the projected browser contents are in three different tabs.但是,投影的浏览器内容位于三个不同的选项卡中。 Currently, I have to switch focus to that projected window and deftly use Ctrl-Tab to get the tab I want to control to become the active tab.目前,我必须将焦点切换到投影的 window 并巧妙地使用 Ctrl-Tab 让我想要控制的选项卡成为活动选项卡。

How do I programmatically select which tab to become active?如何以编程方式 select 哪个选项卡变为活动状态? If there's no generic method, I am happy to have a solution just for Chrome or Edge.如果没有通用方法,我很乐意为 Chrome 或 Edge 提供解决方案。

If the tabs are opened with window.open , you can switch between them using focus() .如果使用window.open打开选项卡,则可以使用focus()在它们之间切换。 The sample code is like below:示例代码如下:

<input type="button" onclick="window1.focus()" value="switch to window1" />
<input type="button" onclick="window2.focus()" value="switch to window2" />
<script>
    var window1 = window.open("https://samplesite.com/window1");
    var window2 = window.open("https://samplesite.com/window2");
</script>

If not, it's impossible to switch between the tabs due to security reasons.如果没有,由于安全原因,无法在选项卡之间切换。 If it were possible, it would be a risk that attackers would find a way to gain access to information about the other tabs a user has opened.如果可能的话,攻击者可能会找到一种方法来访问有关用户已打开的其他选项卡的信息。

Besides, if you're making a browser extension, you can switch between tabs using chrome.tabs API .此外,如果您正在制作浏览器扩展程序,您可以使用chrome.tabs API在选项卡之间切换。 For more information and sample code, you can refer to this answer .有关更多信息和示例代码,您可以参考此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM