Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble displaying an image from Google Drive

I'm struggling to show an image from Google Drive on my HTML page using JavaScript. Following online guides hasn't quite solved it for me.

HTML (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Drive Image</title>
</head>
<body>
  <img id="imageElement" alt="A lovely image">
  <script src="script.js"></script>
</body>
</html>

JavaScript (script.js):

const fileId = '1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome';
const imageElement = document.getElementById('imageElement');

async function fetchGoogleDriveImage(fileId) {
  try {
    const response = await fetch(`https://drive.google.com/uc?id=${fileId}`);
    const url = URL.createObjectURL(await response.blob());
    imageElement.src = url;
  } catch (error) {
    console.error('Error fetching the image:', error);
  }
}

fetchGoogleDriveImage(fileId);

Context:

  • Image in Google Drive is set to "Anyone with the link can view."
  • Despite that, the image doesn't load in the browser, and the console shows an error.

Additional HTML (with pure html):

<body>
  <img src="https://drive.google.com/uc?id=1BEW9tkgVKlp_ebUc17LkXDH-mnPc4ome" alt="Your Image Alt Text">
</body>

CodePen Example

Any help is appreciated! Thanks.

like image 285
Raúl Peñate Avatar asked Feb 01 '26 22:02

Raúl Peñate


2 Answers

I have the same problem. A temporary solution is to use a drive file thumbnail with a large width.

<img src="https://drive.google.com/thumbnail?id=xxxxxxxx&sz=w1000">
like image 160
Tu Nguyen Avatar answered Feb 03 '26 12:02

Tu Nguyen


Though not published anywhere (that I've found), Google Drive's servers have begun rejecting requests where these two headers are attached:

sec-fetch-mode: no-cors
sec-fetch-site: cross-site

If you navigate your browser directly to the (direct link) URL of the file, (i.e. take your src URL and just paste it into the browser nav bar), the sec-fetch-mode header during that request will be set to navigate and it works just fine.

But, as with your <img> example, if the source of the request is a web page, and which is not the same origin as drive.google.com, hence the problem. (Your browser will automatically set those sec-fetch-mode and sec-fetch-site headers as part of the request.)

This appears to be an undocumented change by Google Drive that started on January 10, 2024 and I still can't find any mention of it anywhere, so it's unknown if this behavior will persist or if it reflects an accidental change or oversight.

like image 29
mmuurr Avatar answered Feb 03 '26 12:02

mmuurr