Utilizing button clicks to send fetch commands and extract data from websites

I need help with my Google Chrome extension. I have some fetch commands for an API, but I'm not sure how to send them when a button is clicked. Can someone guide me on the right approach?

Is there a recommended method for a Chrome extension to extract data from a progress bar, like from YouTube, and display it within the extension while still maintaining functionality such as rewinding and fast forwarding?

My end goal is to create a popup that resembles the image linked below where clicking a button triggers the API call or fetch commands to be sent (using YouTube as an example). 1

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Using Sequelize's Op.and and Op.like operators led to an unexpected outcome of producing an empty

I am working on developing a search endpoint using express and sequelize. I noticed an issue where using Op.and in my 'where' object results in an empty object: const where = { [Op.and]: req.query.q.split(" ").map((q) => { ...

Overlapping Divs and Colliding Elements

I am currently exploring the moment when my two yellow divs will overlap and make contact with each other. It seems that the collision detection is triggering true even when the divs are not intersecting. If you'd like to take a look at the example, ...

Utilizing the this.setState function within a callback

In my current project, I've encountered an issue with setting the state in a Twitter timeline react component. The code snippet causing trouble is as follows: componentWillMount: function() { twitter.get('statuses/user_timeline', ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

Can we limit the text in a specific cell to one line on a desktop for a responsive table?

I am facing a challenge with making the second cell in my table have a width of 100% while ensuring that the text stays on one line. While the mobile version is functioning correctly, I am struggling to find a solution for the desktop version as the last ...

What is the best way to implement asynchronous image loading on hover events in React.js?

You may have come across this type of effect before. A good example can be found here - https://codepen.io/anon/pen/GEmOQy However, I am looking to achieve the same effect in React. While I understand that I can use the componentDidMount method for AJAX c ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...

Is it possible to resize an image to fit within its parent div using only the parent div

Is there a way to ensure that an image inside a div resizes itself based on the dimensions of the div without distorting the ratio? <div class="w-50"> <img src="" class="w-full h-full image-cover"> </div> ...

Utilize PHP server to serve index.html for all routes with the combination of React and react-router-dom

Usually, I develop websites using a combination of reactjs, node, and express, then deploy them to Heroku. Everything works smoothly with this setup. However, I recently received a request to create a reactjs frontend with a PHP backend and deploy it to c ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

What is the best way to reset an angularJS form after it has been submitted

I am trying to figure out a way to clear form fields on a modal window after the user executes the save method. I have attempted using $setPristine in AngularJS, but it's not working as expected. Any suggestions on how to achieve this task? Here is t ...

What is the best way to toggle the visibility of my menu using JavaScript?

I recently implemented a script to modify a CSS property in my nav bar as I scroll down, triggering the change after reaching 100px. $(window).scroll(function() { var scroll = $(window).scrollTop(); //console.log(scroll); if ...

implement a JavaScript function for sprite toggling

I have been working on a JS/jQuery function to switch the position of an icon sprite. I have successfully created the following code: $('.toggle-completed').mouseup(function(){ var sp = ($(this).css('background-position')); $(this).css ...

The logo in the Bootstrap 4 beta navbar-brand does not dynamically resize when the navbar collapses, even with the img

Bootstrap 4 Beta Usage Incorporating a logo and inline menu links in the responsive navbar of my website has been a challenge. While the navbar collapses appropriately with viewport changes, the logo fails to shrink proportionately. This results in the ha ...

Displaying a loading template within an Angular component

While reviewing some code in AngularJS version 1.2.22, I came across the following snippet in the HTML: <div class="mainContent" ng-include="content"> </div> Within its corresponding controller, I found this: $scope.content = 'templates ...

Steps to create a translating floating chat button on your website

Hello there! I am attempting to replicate the style of a Floating Website Chat Button. When a user clicks on the large button, I want it to disappear and transform into a chat box. Something similar to this example: https://codepen.io/neilkalman/pen/VPJpaW ...

Transform all Date fields in the Array to a standardized date format

I have an array with various fields, including a field called dateofbirth. I need to remove the time and change the format to MM-DD-YYYY. var records = [ { "recordno":"000001", "firstname":"Bo", "middlename":"G", "lastn ...

The specified selector is invalid or illegal in HTMLUnit

Attempting to mimic a login using htmlunit has presented me with an issue despite following examples. The console messages I have gathered are as follows: runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' erro ...

Obtaining POST request parameters in an Express server

Below is the code snippet for adding a product using an angular service. The product is passed as the body. addProduct(product): Observable<any> { return this.http.post<Observable<any>>( `http://localhost:4401/api/products`, ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...