In a Chrome extension, you can open a link in a new tab using JavaScript by leveraging the chrome.tabs.create() method provided by the Chrome extension API. Here’s how you can do it:
javascript Copy code // Example code to open a link in a new tab chrome.tabs.create({ url: “https://example.com”, active: true }); This code snippet will open a new tab with the URL “https://example.com”. The active: true option ensures that the newly opened tab becomes the active tab.
Make sure to include this code within your Chrome extension’s background script, popup script, or content script, depending on where you want the link to be opened from.
For instance, if you want to open a link in a new tab when a user clicks on a browser action icon (popup), you can include this code in your popup script.
First we write the following JavaScript
document.addEventListener('DOMContentLoaded', function() {
const link = document.getElementById('myLink');
link.addEventListener('click', function() {
chrome.tabs.create({ url: "https://example.com", active: true });
});
});
Then we write the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>Popup</title>
<script src="popup.js"></script>
</head>
<body>
<a href="#" id="myLink">Open Example.com in New Tab</a>
</body>
</html>
This code creates a popup with a link. When the user clicks on the link, the chrome.tabs.create() method is called to open “https://example.com” in a new tab.