I'm making a Google Chrome extension and I have some fetch commands of an API. How do I send them when I click a button? Or what do I do?
What's the best way for a Chrome extension to scrape the progress bar? Let's say from YouTube and put it into the extension, so that it also still works and so I can rewind and fast forward?
end goal is to look something like this its a popup and when I click play or any button it send the api call or fetch commands (youtube is just an example) 1
You should implement a background script with a function to perform the API call. The reason I recommend performing this call in the background is it will be handled independent of the lifetime of the tab: if user closes tab the api call does terminate with the tab. In your manifest you will need to add reference to the background script and host permission for the server domain, unless the server has a policy to enable CORS from anywhere.
To get the button click to call the api function in the background, use message passing: on button click, you send a message from the tab with the button, and in the background service worker implements a listener to receive these messages. When the background listener receives a button click message, it then performs the API call. The message can include additional data if the API call needs some arguments.
In terms of code you will need the following:
service_worker.js
// implement 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 this to perform API call
}
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
// add button onclick/onkeypress handler
button.onclick = sendMessage;
function sendMessage(args){
chrome.runtime.sendMessage({api: "call api", my_arg:1});
}