Search code examples
google-chrome-extension

How to open a manipulated URL in a new tab without a pop-up


I got the extension to add "dev." to the current URL in a new tab which is working through a pop-up.

I'm trying to disable/remove the pop-up so that the code will work only when pressing the extension button instead.

popup.js:

document.addEventListener("DOMContentLoaded", function() {
        console.log("Extension button clicked!");
    var button = document.getElementById("change-url");
    button.addEventListener("click", function() {
        chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            var url = new URL(tabs[0].url);
            url.hostname = "dev." + url.hostname;
            chrome.tabs.create({ url: url.toString() });
        });
    });
});

manifest.json:

{
    "name": "My URL Changer",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["scripting"],
    "host_permissions": ["<all_urls>"],
    "action": {
        "default_popup": "popup.html",
        "default_title": "My URL Changer"
    }
}

popup.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My URL Changer</title>
        <script src="popup.js"></script>
    </head>
    <body>
        <h1>My URL Changer</h1>
        <button id="change-url">Change URL</button>
    </body>
</html>

Solution

  • As woxxom mentioned, the chrome.action.onClicked API is a good fit for this.

    The event does not fire if the extension has a popup, so you'll want to remove the default_popup key. However, you'll need to keep the empty action object. This tells Chrome to show an icon for your extension and is also required to make the API available.

    With those changes in mind, your manifest would look like this:

    {
      "name": "My URL Changer",
      "version": "1.0",
      "manifest_version": 3,
      "permissions": [
        "scripting"
      ],
      "host_permissions": [
        "<all_urls>"
      ],
      "action": {}
    }
    

    You should also consider removing <all_urls> and replacing it with just the domains you want your extension to run on, since it's always best to request just the access you need. You could also remove this key entirely and use the activeTab permission instead, which gives your extension access to pages only when the action icon is clicked.

    You'll then need to declare a service worker by adding the following to your manifest:

    "background": {
      "service_worker": "worker.js"
    }
    

    And in worker.js, you can copy your code from popup.js making sure to use the action API instead of DOMContentLoaded.