2

I would like to call an API when a button is pressed on extension popup. But the API is not called and unable to retrieve any response from fetch API.

I tried the followings:

  • Added API endpoint to host_permissions in manifest file.
  • Created a UI with a button. The UI shows when I click the extension icon.
  • In popup.js, added event handler to the button. When button is clicked it sends a message to the background.js file with API URL.
  • In background.js, I have added a listener to listen the message and call the API.

manifest.js

{
    "name": "Product Extractor Extension",
    "description": "Extract product data from predefined websites.",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": [
        "storage",
        "activeTab",
        "scripting"
    ],
    "host_permissions": [
        "https://jsonplaceholder.typicode.com/*"
    ],
    "action": {
        "default_popup": "popup.html",
        "default_title": "Kevin"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ],
    "background": {
        "service_worker": "background.js"
    }
}

popup.html

 <button class="signInButton" id="signInButton">
     Sign In
 </button>

popup.js

document.getElementById("signInButton").onclick = function() {
  chrome.runtime.sendMessage({
    contentScriptQuery: "userLogin",
    url: 'https://jsonplaceholder.typicode.com/todos/1'
  }, function(response) {
    console.log(response);
  });
}

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    switch (request.contentScriptQuery) {
        case "userLogin":
            fetch("https://jsonplaceholder.typicode.com/todos/1")
                .then((response) => response.json())
                .then((json) => sendResponse("kerk"));
            break;
    }
    return true;
});
Raiyad Raad
  • 482
  • 5
  • 17
  • 1
    The code is fine. Make sure you look at the correct console: right-click inside the popup and select "inspect" in the menu. Also check [background.js console](/a/10258029). BTW you don't need messaging here: you can make the request in the popup script directly. – wOxxOm Apr 16 '22 at 06:22
  • Your code is working fine. I'm using that – siva hari Jul 03 '22 at 06:46

0 Answers0