javascriptbrowserblobcreateobjecturlsecurity-warning

How to load a blob URL that's not marked as insecure?


If you go to the "creating a blob" example in https://developer.mozilla.org/en-US/docs/Web/API/Blob#creating_a_blob, you end up getting an URL that starts with "blob:https://", but the browser marks the site as insecure: enter image description here

What is required for that to be marked as secure?

To give context of what I'm doing: I have an angular app that can open PDF's from base64 data in new tabs, and this can be any number of PDF's at the same time.


Solution

  • Viewing the pdf through the blob URL (blob:https://...) isn't dangerous (unless of course the pdf has something dangerous inside). You can safely ignore the warning.

    That warning message comes from the fact that your current URL is not using HTTPS, but blob urls are pointing to a piece of local data in the browser, you don't need a transfer protocol for that.

    Here's a good answer describing blob urls in detail: https://stackoverflow.com/a/30881444/12914833

    But blob URLs aren't really meant for navigating to. They are meant for the src attribute of HTML elements, or for a download link via the a tag. Here are the elements that support src: https://www.w3schools.com/tags/att_src.asp

    Here's an example of how you would use a blob url:

    // This function would retrieve a blob from somewhere
    // I'm just fetching an image and converting it for convenience
    function getBlob() {
      return fetch(
        'https://wealthofgeeks.com/wp-content/uploads/2022/07/spongebob-rainbow-meme-imagination.jpg'
      ).then((res) => res.blob());
    }
    
    getBlob().then(
      (blob) => (document.querySelector('img').src = URL.createObjectURL(blob))
    );
    <img width=300></img>

    And here's an example of how to allow downloading the blob.

    // This function would retrieve a blob from somewhere
    // I'm just fetching a pdf and converting it for convenience
    function getBlob() {
      return fetch('https://uclit.ca/assets/documents/dummy.pdf').then((res) =>
        res.blob()
      );
    }
    
    getBlob().then((blob) => {
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.textContent = 'DOWNLOAD';
      a.download = 'dummy.pdf';
      document.body.append(a);
    });
    

    This won't work in a sandboxed iframe like a snippet, so here is a stackblitz: https://stackblitz.com/edit/typescript-t5dqpa?file=index.ts,index.html


    For viewing pdfs without that warning you can either:

    1. Embed it into an html page
    2. Host the file on a server
    3. Let the user download the file