u936293
u936293

Reputation: 16244

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. (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.

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.

How do I programmatically select which tab to become active? If there's no generic method, I am happy to have a solution just for Chrome or Edge.

Upvotes: 1

Views: 2255

Answers (1)

Yu Zhou
Yu Zhou

Reputation: 12971

If the tabs are opened with window.open, you can switch between them using 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. For more information and sample code, you can refer to this answer.

Upvotes: 0

Related Questions