Download attribute on link not working? How to fix it.

May 17, 2023 | WordPress

One of my clients recently approached me with an issue regarding image downloads on their website. I had created some download buttons that, when clicked, were supposed to download the images they were placed on top of. However, this functionality had stopped working correctly. Instead of downloading the image, it would open the image in the browser. While it was still possible to right-click and save the image, not everyone is aware of this workaround.

Upon reviewing their website, I realized that I had made a change that served images and PDFs through a CDN. Consequently, the download button was no longer working as intended, since the files were being served from a different website. Naturally, my initial reaction was panic, and I started considering numerous impractical solutions to fix the issue. Could I modify the plugin I was using to exclude images served on product pages? However, in this particular case, I was utilizing the Ewww image optimizer, which only allowed excluding paths to files one by one. Given the site’s substantial number of files and the likelihood of the client adding more, this approach was not feasible.

Fortunately, solutions to most problems tend to be simpler than we initially imagine. In this case, a straightforward JavaScript script provided the answer. Here’s how it works:

  1. Use querySelectorAll to select all “a” tags that include a “download” attribute.
  2. Iterate through the links and employ “new URL(link.href)” to obtain the URL object for each link.
  3. Set “url.protocol” to ‘https’ (optional but recommended to address any insecure content issues).
  4. Set “url.host” to “sitedomain.com.” Remember to replace “site domain” with your website’s actual domain.
  5. Update “link.href” with “url.href.”

By following these steps, your file downloads should work flawlessly once again. Below is the complete code:

const links = document.querySelectorAll('a[download]');
links.forEach(link => {
  const url = new URL(link.href);
  url.protocol = 'https';
  url.host = 'sitedomain.com';
  link.href = url.href;
});