Redirect to url Using Google chrome Extension

10,131

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);
});
Share:
10,131
Jot Dhaliwal
Author by

Jot Dhaliwal

Updated on June 04, 2022

Comments

  • Jot Dhaliwal
    Jot Dhaliwal almost 2 years

    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?

  • Jot Dhaliwal
    Jot Dhaliwal almost 10 years
    What i have to do if i want to open the given url in next tab?
  • Rob W
    Rob W almost 10 years
    @Jatt.net-Born2Code Use chrome.tabs.create.
  • Jot Dhaliwal
    Jot Dhaliwal almost 10 years
    thnx for cooooooooooooooooooooooooooooooooooooooooool answer,,,