2

I am new to Google Chrome Extensions. I have created a button in my extension. With that button I want to redirect the user to another site (like "www.example.com"). I have the following code which I wrote for the redirection, but it doesn't work.

Related question.

manifest.json

{
    "name": "Popup ",
    "manifest_version": 2,
    "version": "0.1",
    "description": "Run process on page activated by click in extension popup",
    "browser_action": {
    "default_icon": "icon.png",
        "default_popup": "popup.html"
    },

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

popup.html

<html>
    <head>
        <script src="popup.js"></script>
        <style type="text/css" media="screen">
            body { min-width:250px; text-align: center; }
            #click-me { font-size: 15px; }
        </style>
    </head>
    <body>
        <button id='click-me'>Click Me!</button>
    </body>
</html>

background.js

chrome.extension.onRequest.addListener(function(request, sender) {
    chrome.tabs.update(sender.tab.id, {url: request.redirect});
});

popup.js

function clickHandler(e) {

    chrome.extension.sendRequest({redirect: "https://www.google.co.in"});
    alert("url");

    this.close();
}

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('click-me').addEventListener('click', clickHandler);
})

Do you have any idea why it doesn't work?

Community
  • 1
  • 1
Jot Dhaliwal
  • 1,470
  • 4
  • 26
  • 47

1 Answers1

14

If you use background pages, then you need to declare the background script (background.js in your case) in the manifest file:

  "background": {
      "scripts": [ "background.js" ]
  },

Your example will not work though, because sender.tab is only defined if the request came from a tab or content script, not from the popup.

In your example, there is no need for a background page at all, you can just use the chrome.tabs API directly from the popup page:

function clickHandler(e) {
    chrome.tabs.update({url: "https://example.com"});
    window.close(); // Note: window.close(), not this.close()
}
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('click-me').addEventListener('click', clickHandler);
});
Rob W
  • 341,306
  • 83
  • 791
  • 678