Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file.

Interestingly, this function performs as expected in Chrome.

@action
  async loadVoucher(id, fiscalId) {
    const pdf = await this.httpClient.get(...);

    console.log("load Voucher: ", pdf);

    const blob = new Blob([pdf.data], { type: "application/pdf" });
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = "Dossier_" + new Date() + ".pdf";

    console.log("before link click");

    link.click();
    link.remove();
  }

The usage of @action is derived from mobx. However, when testing this functionality in Firefox, the second console log (before click link) appears in the browser console (first log displays the data correctly), but the download process fails to initiate.

Iā€™m puzzled by this issue ā€“ any insights on what might be going wrong?

Answer ā„–1

If you want to make it work in Firefox, simply ensure the created element is added to the DOM:

<div class="button" id="test">Create File</div>

    $('body').on('click', '#test', function(event) {
        var link = document.createElement('a');
        // Make sure to append the element to the DOM
        document.body.appendChild(link);
        link.setAttribute("type", "hidden"); // You can hide it if necessary
        link.download = 'test.xls';
        link.href = 'data:application/vnd.ms-excel;utf-8,test';
        link.click();
    });

Check out the codepen example - http://jsfiddle.net/b40af6rm/

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

Javascript Code Tweaking... Is it Just a Minor Oversight?

I've been working on incorporating a jQuery Exit LightBox into my website and came across this straightforward tutorial - The concept of the pop-up is quite clever, but I've run into an issue where it only functions properly when a visitor is at ...

Communication with child processes in node.js is not done using the child_process module

Hello Everyone, I'm currently experimenting with node.js to utilize JS plugins developed by others using the child_process API. However, I'm facing an issue where the child process is not able to communicate effectively with the parent process. ...

Error: Unable to access the 'version' property of null

Having trouble installing any software on my computer, I've attempted various solutions suggested here but none have been successful. $ npm install axios npm ERR! Cannot read property '**version**' of null npm ERR! A complete log of this ru ...

What is the method for adding pages to the ion-nav component in Ionic with Angular?

How can I implement a UINavigationController-like functionality in iOS using an ion-nav element? The example provided here is in Javascript, but I need assistance with implementing it in Angular. Specifically, I'm unsure of how to programmatically add ...

Using JavaScript to develop a demonstration of the capabilities of Microsoft's Cognitive

Having trouble getting this basic example of the Microsoft Cognitive Services to work in JavaScript. Need some help or a working example, please! I've attempted to run the code in both node and browser with necessary modifications. Encountering an e ...

Locate the index of each distinct element within the array

Let's define an array called 'arr' with some elements: [7, 9, 30, 40, 50, 8, 1, 2, 3, 40, 90,2, 88,1] We also have another output array defined as: [0, 1, 2, 3, 4, 5, 6, 7, 8 ,10, 12] I stored this code snippet on a javascript ...

Is it possible to dynamically create input fields in AngularJS by clicking a button?

I'm currently working on a project that involves adding an input field and a button each time a user clicks on the button. Is there a way to retrieve the text from the input field when the new button, which is displayed alongside the input field, is ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

Building a Div Tag Layout with CSS for Full Width and Left Position of 300px

Experiencing some trouble with styling a div element. My goal is to have the div start at left:300px and stretch across the entire width of the browser window. However, when I apply width:100%, the div extends beyond the boundaries of the browser screen. ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator: ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'" To access these elements, we can compile all the ones with fa-minus and store them in a lis ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

Node and Web scraping Promise: a powerful combination

I've been using Cheerio and Node for web scraping, and I thought implementing promises could simplify handling asynchronous code. However, my attempt to chain promises hasn't been successful. Below is the code I'm working with, in hopes that ...

Transform Objects Array from AJAX Response into a Distinct JSON Entity

I am encountering a problem with a sample endpoint that is returning [object Object] for JSON data, and I can't figure out why. Mock API Initially, my code was a bit confusing, but fortunately, I found a clearer solution in another answer. functio ...

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

Ending an $.ajax request when the page is exited

Currently, I have a function set on a timer to retrieve data in the background: (function fetchSubPage() { setTimeout(function() { if (count++ < pagelist.length) { loadSubPage(pagelist[count]); fetchSubPage(); ...

Implementing an onclick event listener in combination with an AJAX API call

I'm really struggling with this issue. Here's the problem I'm facing: I have a text area, and I need to be able to click on a button to perform two tasks: Convert the address text into uppercase Loop through the data retrieved from an API ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format. app/controllers/rando ...

Trouble arises when incorporating a new feature onto a map with OpenLayers and Vue.js

I'm currently working on integrating a custom control into my map using OpenLayers with Vue.js. The Explore.vue component is responsible for creating the "map" (olmap) with OL, and I bind it to the child component LeftSideBar2.vue. However, when att ...