'Google Chrome Extension Manipulate URL

I'm making a Chrome Extension that manipulates the current tabs. When I give it the specific URL, it works.

<html>
  <script>

function updateUrl(tab){

      var newurl = "http:www.google.com";
      chrome.tabs.update(tab.id, {url: newurl});
}

chrome.browserAction.onClicked.addListener(function(tab) {updateUrl(tab);});

  </script>
</html>

However, when I change it to the following, it doesn't work.

<html>
  <script>

var currentURl = tab.url

function updateUrl(tab){

      var newurl = currentURL.replace("bing", "google");
      chrome.tabs.update(tab.id, {url: newurl});
}

chrome.browserAction.onClicked.addListener(function(tab) {updateUrl(tab);});

  </script>
</html>

I have tried changing the "tab.url" to things such as "chrome.tab.url" "chrome.tabs.url" and a number of others.



Solution 1:[1]

tab is undefined in the assignment

var currentURL = tab.url

You must define currentURL within your function updateUrl.

Try:

<html>
   <script>

   function updateUrl(tab){

       var currentURL = tab.url

       var newurl = currentURL.replace("bing", "google");
       chrome.tabs.update(tab.id, {url: newurl});
   }

   chrome.browserAction.onClicked.addListener(function(tab) {updateUrl(tab);});

  </script>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vinzee