Search code examples
javascriptsafarimobile-safari

Safari reload page after saving image by user


I try to download an image in blob: create a link element, set download and href attributes. But for two different apps the same script has different behavier: in the simplest and light app there is no page reloading after user confirm downloading, image has downloaded. But in the other - unwanted reload after an image was downloaded. Can I avoid this somehow? Problem ocures only on Safari mobile browser.

Below is a snippet I use:

const image = 'data:image/jpeg;base64,' + event.detail;
fetch(image)
  .then(res => res.blob())
  .then(blob => {
     let file = new File([blob], 'MyImageName.jpeg', {type: blob.type, lastModified: Date.now()});
     files.push(file);

     if (
       navigator.canShare && 
       navigator.canShare({ files }) && 
       navigator.userAgent.indexOf("YaBrowser") == -1
     ){
       //This part works well
       ...
     } else {
       //This part works not as expected in Safari
       downloadLink.download = "MyImageName.jpg"
       downloadLink.innerHTML = "Download";
       downloadLink.href = image;
     }
  });

Besides, a button "View" in the confirm messege does not works, just reloads a page.


Solution

  • This is Safari bug. Solved by creating image preview and adding for user a tip to use native Safari functionality for images:

    const image = 'data:image/jpeg;base64,' + event.detail;
    fetch(image)
      .then(res => res.blob())
      .then(blob => {
         const preview = document.querySelector('#photoPreview');
         preview.src = image;
    
         let file = new File([blob], 'MyImageName.jpeg', {type: blob.type, lastModified: Date.now()});
         files.push(file);
    
         if (
           navigator.canShare && 
           navigator.canShare({ files }) && 
           navigator.userAgent.indexOf("YaBrowser") == -1
         ){
           ...
         } else {
           btnShareDownload.innerHTML = "Tap and hold image to save or share";
         }
    });