Search code examples
javascriptreactjsredux-thunkimagedownload

How to get noticed image was downloaded to be able to start a new task?


I would execute following two tasks one after the other:

  1. download image save to disk
  2. call a backend method and then navigate to Instagram
<a
  data-lightbox-anima="fade-top"
  className={`btn`}
  download={`${organizationShortId}-${programId}`}
  href={`/t44-post-cover/${organizationShortId}-${programId}`}
  onClick={(e) => {
    dispatch(
      createShare({
        props: {
          tempUserShortId: getTempUserShortId(),
          postId,
        },
        andThen: (_) => {
          if (
            confirm(
              "Megnyitom az Instgramot, s megosztom az utoljára mentett animációt!"
            )
          ) {
            router.push(`https://www.instagram.com`);
          }
        },
      })
    );
  }}
>
  Insta
</a>

Unfortunately in mobil only download get started and finished, but confirm dialog will not appear anymore. What can I do to do both task?

enter image description here

enter image description here


Solution

  • To my best knowledge, there is no browser event that could tell you when a download initiated by your page has finished.

    You'll need to initiate a download, wait for a bit (to hope it has started and/or finished), and then continue doing what you want to do:

    export default function initiateDownload(url, download, delay) {
      return new Promise((resolve) => {
        const aElement = document.createElement('a');
        aElement.href = url;
        aElement.download = download;
        document.body.appendChild(aElement);
        aElement.click();
        setTimeout(() => {
          const parentNode = aElement.parentNode;
          if (parentNode) {
            parentNode.removeChild(aElement);
          }
          resolve();
        }, delay);
      });
    }
    
    ...
    
    await initiateDownload(
        `/t44-post-cover/${organizationShortId}-${programId}`,
        `${organizationShortId}-${programId}`,
        1000,  // wait for a second
    );
    
    ... do other things...