2

I'm trying to write a chrome extension and cannot seem to understand how to implement the following scenario:

  • user is on page X
  • user clicks on the extension's button
    • something happens (specifically, user is redirected to some url)

here's the manifest.json:

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "my title"
    },

  "content_scripts": [
      {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["myscript.js"]
      }
  ],


  "permissions": [
    "tabs", "https://*/*"
  ]

}

and here's myscript.js:

alert('entered myscript.js..');

function doMagic()
{
    alert('extension button clicked!!');
}

chrome.extension.onClicked.addListener(doMagic);

i know im missing something really obvious, but cant seem to figure it out from the docs, other sites, etc.!!

1 Answer 1

5

Don't use a content_script, you really only need those if have to have access to the HTML of the tab.

Use a background_page for the onClicked listener and chrome.tabs.update to redirect the page.

function doMagic(tab) {
  chrome.tabs.update(tab.id, { url: 'http://www.google.com' });
}
chrome.browserAction.onClicked.addListener(doMagic);
Sign up to request clarification or add additional context in comments.

7 Comments

thanks...that's what i just started trying, but for the life of me I cannot redirect the tab's url!!! for e.g.: this works fine: chrome.tabs.create({url:"google.com"}); but this doesn't: chrome.tabs.update({url:"google.com"});
I added some example code that should redirect the current tab when the browserAction button is clicked.
ahhh! thanks a lot!! this works great!...I have one more question though: how does one access the url of the current tab?
found it, it's simply tab.url...going crazy here....thanks for all your help!!i have to say, chrome's docs suck big time
I'd just like to say that the Chrome documentation is fantastic, provided it's read properly to learn the quirks. I've very rarely found something missing and never anything to be incorrect. Google are very good at writing helpful documentation and spend a lot of time and money on it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.