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;
});