Search code examples
javascripthttp-redirectgoogle-chrome-extensionfirefox-addon

Change and open current tab URL to something else after clicking a button in chrome extension using Javascript


I need a help in changing the current tab URL to something else; let's say; https://stackoverflow.com/ using my chrome extension;

my javascript code is :

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var tab = tabs[0];
console.log(tab.url);
});

In this code tab.url returns the URL of current page. i want to do something like this-

if(tab.url=="https://www.google.com/")
 {
     //redirect this page to  https://stackoverflow.com/
 }
else
 {
   //stay on the same page
 }

basically what i want to achieve from the extension is to redirect to stackoverflow when the current tab is google.com


Solution

  • Is this what you're looking for?

    let newUrl = "https://stackoverflow.com/";
    if(tab.url=="https://www.google.com/")
        chrome.tabs.update(undefined, { url: newUrl });
    

    source