0

I would like to know how to download image using javascript. It downloads but shows failed error,

<div>
<button onClick=this.downloadImage(event, "http://example.net/media/image.png")>Download</button>
</div>  



  downloadImage = (event, image) => {
      var link = document.createElement('a');
      link.href = image.toDataUrl("image/png", 1.0);
      link.download = 'Download.png';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
  }


1
  • The parameter image does only contain the URL-string to you image. This should show something like "toDataUrl is not a function". Commented Mar 31, 2020 at 5:46

1 Answer 1

1

You can use download API.

According Developer Mozilla's site, try it out:

function onStartedDownload(id) {
  console.log(`Started downloading: ${id}`);
}

function onFailed(error) {
  console.log(`Download failed: ${error}`);
}

var downloadUrl = "https://example.org/image.png";

var downloading = browser.downloads.download({
  url : downloadUrl,
  filename : 'my-image-again.png',
  conflictAction : 'uniquify'
});

downloading.then(onStartedDownload, onFailed);

Here is more info, https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads/download

Btw, don't forget about CORS and it's limits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.