One effective approach is to create a background script containing a function to execute the API call. The advantage of running this call in the background is that it operates independently of the tab’s lifespan: even if the user closes the tab, the API call continues to function. To integrate this setup into your project, you must reference the background script in your manifest file and specify host permissions for the server domain, unless the server allows CORS from any source.
To trigger the API function when a button is clicked, you can utilize message passing: when the button is clicked, a message is sent from the button-containing tab to the background service worker, which then listens for and processes these messages. The message can also contain any necessary parameters for the API call.
Below is an outline of the code you will need:
service_worker.js
// set up listener to receive messages from tabs
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.api)
callApi(request.my_arg)
}
);
function callApi(arg){
// implement API call logic here
}
manifest.json
"host_permissions": [
"https://your-api-domain.com/*"
],
"background": {
"service_worker": "service-worker.js"
},
"content_scripts": [
{
"matches": [ "YOUR MATCH PATTERN HERE" ],
"js": [ "content-script.js" ]
}
]
content-script.js
// set up button onclick/onkeypress event handler
button.onclick = sendMessage;
function sendMessage(args){
chrome.runtime.sendMessage({api: "call api", my_arg:1});
}