0

I would like to download certain object stored in state (React) by clicking button that is present in DOM. Thing is I want to avoid creating extra DOM element and force clicking it (not sure if it's possible tho).

By clicking button I am launching class method where e (event) is an argument. Inside this methodI have created new Blob object with two arguments:

var blob = new Blob([JSON.stringify([...this.state.data])], { type: "application/json" })
//also tried text/json

then I assigned referrer and download properties as below:

e.target.href = URL.createObjectURL(blob)
e.target.download = "data.json"

Console says everything seems to be all way set:

Blob { size: 495, type: "application/json" } blob:http://localhost:3000/aa517a7b-2e7d-46a8-8949-c8946947ff51 data.json

But the above doesn't work, download action is not getting triggered. Does it mean I need to 'click' blob link once more? If so, then how can I perform this if I already have triggered click event by clicking 'Download JSON' button? Note that I don't want to create another DOM element.

I tried it on both Chrome and FF and got the same result.

Mateusz Osuch
  • 388
  • 1
  • 4
  • 14
  • You have to create a new DOM element. Why dont you want that? – Jonas Wilms Mar 31 '19 at 10:30
  • Just don't get the point of such action. IMO it's quite pointless since I have everything to download this object: Click to download -> Create Blob -> Create extra element -> Click it again – Mateusz Osuch Mar 31 '19 at 10:37
  • 1
    Yes, it is pointless ... but it works. – Jonas Wilms Mar 31 '19 at 10:44
  • @JonasWilms so again, I wouldn't mark my question as duplicate since my conditions are slightly different unless you found quite the same as mine question asked with proper answer. Even 'not possible' answer will be highly appreciated. Thanks – Mateusz Osuch Mar 31 '19 at 10:46

0 Answers0