Chrome open link in new tab and switch to it

You can use the following JavaScript code to open a link in a new tab and then switch to it:

chrome.tabs.create({ url: 'https://www.example.com' }, function(tab) {
  chrome.tabs.update(tab.id, { active: true });
});

Here's how it works:

  1. chrome.tabs.create() creates a new tab with the specified URL.
  2. The callback function is called with the new tab's ID as an argument.
  3. chrome.tabs.update() updates the new tab to make it active.

You can also use the chrome.tabs.executeScript() method to inject a script that opens the link in a new tab and switches to it:

chrome.tabs.executeScript({
  code: 'window.open("https://www.example.com", "_blank"); window.focus();'
});

This code uses the window.open() method to open the link in a new tab, and then uses the window.focus() method to switch to the new tab.

You can also use the chrome.tabs.onUpdated event to detect when the new tab is ready and then switch to it:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.status === 'complete') {
    chrome.tabs.update(tabId, { active: true });
  }
});

This code listens for the onUpdated event and checks if the new tab is ready (i.e., its status is complete). If it is, it updates the tab to make it active.

Note that these examples assume you have the necessary permissions to interact with tabs. If you're building a Chrome extension, you'll need to declare the "activeTab" permission in your manifest file to use these methods.