Cannot download files using Anchor elements created within HTML elements

The following code is written within the HTML element.

<script>
  const downloadLink = document.createElement("a");
  const fileName = "sample.csv";
  downloadLink.download = fileName;
  downloadLink.href = sampleObjectUrl;
  downloadLink.click();
</script>

It works and downloads fine from my PC browser (Chrome), but not from my smartphone (AndroidOS).
What could be the cause?

I think the download must be triggered by an user action. Something like the user click a button and then you execute your script.

Thanks for answering.
The example I gave above was forcing a click event, but I could not do it by clicking directly on the anchor element on the screen as follows.

<a id="downloadLink">download</a>

<script>
  const downloadLink = document.getElementById("downloadLink");
  const fileName = "sample.csv";
  downloadLink.download = fileName;
  downloadLink.href = sampleObjectUrl;
</script>
```

have you got an example of sampleObjectUrl?

this example works in desktop, android, ios:

<a id="downloadLink">download</a>

<script>
  const downloadLink = document.getElementById("downloadLink");
  const fileName = "helloWorld.txt";
  downloadLink.download = fileName;
  downloadLink.href = 'data:text/plain,HelloWorld!';
</script>

Thanks for even creating the example.
I tried to run the example you created as is, but still could not download the file on android, even though I could on desktop.
It seems that there is another cause.

have you tried on an empty page? what browser are you using? is the link actually reachable or is it covered by a transparent group/element?

The cause was found.
I was using a screen created with .bubble in an app I use at my company, and it seemed to be a limitation of the app.
I was able to download the file from Chrome instead of the app.
Sorry for the trouble.
Thanks for thinking with me.

I’m happy you found a solution :slight_smile:

This topic was automatically closed after 70 days. New replies are no longer allowed.