How to change active tab url in chrome extension

Viewed 3027

I'm discovering how to develop a Chrome extension and I can't find actually how to change the active url. I would like to get informations from websites and pack them.

Actually the first lines of this code work. I've tried different ways to change the url, can't find the right one...

$("body").css('background-color', 'pink');
$("body").html('COUCOU');
setTimeout(function(){ 
      var myNewUrl = "http://www.google.com";
      chrome.tabs.update(active, {url: myNewUrl});
}, 2000);;

My manifest is :

{
  "name": "A browser action with a popup that changes the page color",
  "description": "Change the current page color",
  "version": "1.0",
  "permissions": [
    "activeTab", "tabs"
  ],
  "browser_action": {
      "default_title": "Set this page's color.",
      "default_icon": "icon.png",
      "default_popup": "popup.html"
  },
   "content_scripts": [ {
    "js": [ "jquery.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
  "manifest_version": 2,
  "content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}

Can someone help me?

1 Answers

Let's see the signature of the tabs.update method in the docs:

chrome.tabs.update(integer tabId, object updateProperties, function callback)

integer (optional) tabId
Defaults to the selected tab of the current window.

object updateProperties
[...]

Since you want the current (selected) tab, you can just omit the tabId - it's marked as optional.

chrome.tabs.update({url: myNewUrl});

From a content script, the situation is different. You don't have access to chrome.tabs API.

But you can simply change the document's properties, as you're in the context of the active page already:

document.location = myNewUrl;
Related