Get the image file using JavaScript

I'm wondering how to successfully download an image using javascript. Every time I try, it shows a failed error message.

<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);
  }


Answer №1

To implement downloading functionality, you can utilize the download API.

As per the information provided on Mozilla's developer site, you can try the following code snippet:

function onStartedDownload(id) {
  console.log(`Download initiated: ${id}`);
}

function onFailed(error) {
  console.log(`Download unsuccessful: ${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);

For more details, visit https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/downloads/download

Additionally, ensure to consider CORS and its associated constraints.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Globalization of an Angular2 Meteor Web Application

Creating a web application using Meteor and Angular2 is my current project. With the need for multi-language support in mind, I am referring to Uri Goldshtein's boilerplate at https://github.com/Urigo/angular2-meteor-base as my foundation. What appro ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...

What will occur if I invoke response.end in Node.js while asynchronous I/O operations and callbacks are still executing?

When working with Node.js, what happens if you call "response.end()" while I/O calls and/or callbacks are still being executed? Take a look at the code snippet below: var app = http.createServer(function(request, response) { response.writeHead(200, { ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Having trouble with rendering components in React and Bootstrap?

Attempting to display basic Bootstrap components using React. This corresponds to the index.html file: <!doctype html> <html> <head> <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script> <script src="j ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

What is the best way to hide or show child elements within a tree structure using a toggle function

My HTML code needs to be updated to include a toggle span and JavaScript functionality. This will allow the child elements to be hidden and only displayed when the parent is clicked. I am a beginner with JavaScript and would appreciate any help in resolv ...

Preserve the scroll location when new items are included in the array within ng-repeat

Is it possible to have a list of messages displayed using ng-repeat and load older messages via ion refresher when the user scrolls to the top? The goal is for the older messages to be added above the current messages while maintaining the scroll position ...

Create a mathematical function in MATLAB that involves subtracting and dividing two arrays

I am trying to incorporate this specific equation into my Matlab code: https://i.sstatic.net/yOGAb.jpg The values of 'a' are stored in an array of size 140x1 double called 'approx', the values of 'x' are also in an array of s ...

Using D3.js to customize tick values on an ordinal scale axis

Currently, I am utilizing an ordinal scale for my axis: var xBarScale = d3.scale.ordinal() .rangeRoundBands([0, width], .1) .domain(d3.range(data.length)); var xBarAxis = d3.svg.axis() .scale(xBarScale) .orient("bottom"); Within my data ...

The password encryption method with "bcrypt" gives an undefined result

import bcrypt from 'bcrypt'; export default class Hash { static hashPassword (password: any): string { let hashedPassword: string; bcrypt.hash(password, 10, function(err, hash) { if (err) console.log(err); else { ha ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

Ways to convert a PHP array into a JavaScript array

I have a 3D array in php when using var_dump($arr) it looks like this array(2) { [0]=> array(4) { [0]=> array(2) { [0]=> string(7) "36.3636" [1]=> int(8) } [1]=> array(2) { [0]=> string(7) "27.2727" [1]=> int(5) } [2]=> a ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

Is there a way to automatically zoom in when clicking on a marker and centering the map to that

I have integrated a map into my project where I am currently plotting random coordinates. These coordinates are stored in a data table and everything is functioning smoothly. However, I am facing an issue with implementing a zoom feature using the panTo m ...

Call a React component from an external JavaScript file

I am working on a react application that has a bundle.js file created using webpack containing all the necessary code. Recently, I started developing a separate dotnet application and I need to display the main 'App' component from my react appl ...

Uploading and previewing multiple images on a canvas

After successfully creating single upload for images and placing them on canvas as seen in http://jsfiddle.net/StJnY/, I am now looking to adapt the script for multiple image uploads. Here is how I plan to modify the script: JS : $(function () { $(&a ...

Is it possible to select a file name at random from an array in Processing 2?

I'm currently working on a project in Processing where I need to randomly select a document and print it from the terminal. Specifically, I am having trouble figuring out how to store filenames in an array and then have Processing choose one at random ...

Protecting Angular Routes: Verifying HTTP-Only Cookie Authentication on the Server- CanActivate Function

I am utilizing an HTTP only cookie for authentication in my server: export const checkCookie = async (req: Request, res: Response) => { const token = req.cookies["token"]; if (!token) { return res.status(401).json({ message: "Unau ...

javascript a loop through an array to reassign element ID's

Formulating a form with input elements that are utilizing a jquery datepicker is the current task at hand. Take a look at a snippet of the HTML code for these inputs: <td style="width:15%"><input type="text" name="datepicker" id="Tb3fromRow10"/&g ...