Stephan Yazvinski
Stephan Yazvinski

Reputation: 578

Update and run pre defined link on current tab chrome extension

I'm trying to make a chrome extension go to a predefined link on the currently open tab. I can't figure out how to do this. Any ideas?

Upvotes: 0

Views: 131

Answers (1)

Dinesh Patil
Dinesh Patil

Reputation: 436

Add the following code in the background.js, Which handles the click event on extension.

chrome.browserAction.onClicked.addListener(() => {
    chrome.tabs.query({ active: true }, (tabs) => {
        const tab = tabs[0];
        chrome.tabs.update(tab.id, {
            url: 'https://stackoverflow.com/questions/68945425/update-and-run-pre-defined-link-on-current-tab-chrome-extension',
        });
    });
});

Code Explanation

  1. On-click on the extension, I fetch the active tab information using chrome.tabs.query API.
  2. chrome.tabs.query will return an array of tabs.
  3. Get the 0'th indexed tab from the array and update the URL as per your requirement using chrome.tabs.update API.

Reference https://developer.chrome.com/docs/extensions/reference/tabs/#method-update

Upvotes: 1

Related Questions