Change Chrome Tab with Javascript

Viewed 18619

I'm looking for a way to change tabs (got to the next open tab, which is essentially like holding CTRL and pressing the TAB key) through code on a webpage. I want to be able to click anywhere on the page and it will go to the next tab? I understand the clicking on the webpage part, just not how to access the chrome tabs.

Is this even possible?

Thanks,

3 Answers

As @jim said, it is not possible to switch tabs from within a website using JavaScript. But it can be done using the Chrome Extension Tabs API which is used in Chrome Extensions.

Below is a code snippet from the extension that I'm working on. It would switch to the very next tab when triggered:

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 });
});

I hope this solves your query. Let me know if you have any better suggestions.

If you know the window name (typically if you created the window), and you are on the same domain, you can switch to it with the window name part of the call to 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

The window will reload, so bear that in mind.

If you have access to the tab you wish to switch to, theoretically you could do the following, using postMessages:

// assuming you have this set up:
// https://stackoverflow.com/questions/33957477/cross-domain-localstorage-with-javascript

// 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)

I haven't got the above to work though.

Related