Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set authorization header on background-image: url()?

I am trying to retrieve background images via a REST API.

However, to do so, I need to authorize.

The token is available from the context where the background-image is supposed to be loaded but I have no idea how to add it to the request.

Any ideas? Is this possible at all?

In another approach I used my webserver to add authorization to all requests from within a certain context. This worked fine but is not possible anymore.

like image 841
Moritz Schmitz v. Hülst Avatar asked Oct 31 '25 20:10

Moritz Schmitz v. Hülst


1 Answers

One way would be to request the images via Javascript, set the correct headers and then display the images as an object URL/blob. Here's an example:

fetch('https://i.imgur.com/PLKabDV.png', { headers: {
    "Content-Type": "application/json" // this header is just an example, put your token here
  } })
  .then(response => response.blob())
  .then(blob => {
    let img = document.getElementById('image');
    let url = URL.createObjectURL(blob);
    img.style.backgroundImage = `url(${url})`;
  })
<div id="image" style="width: 430px; height: 430px;"></div>
like image 161
Fabian Schultz Avatar answered Nov 02 '25 08:11

Fabian Schultz