Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
Call API from popup.js to background script through message passing in Chrome Extension

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;
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!