Downloading blocked by CSP

Hello,

In a custom App, I retrieve some JSON content from an API, and I want the user to be able to download a JSON file of this data.

I tried a few things like this :

const downloadTxtFile = () => {
  const texts = ["line 1", "line 2", "line 3"]// file object
  const file = new Blob(texts, { type: 'text/plain' });// anchor link
  const element = document.createElement("a");
  element.href = URL.createObjectURL(file);
  element.download = "100ideas-" + Date.now() + ".txt";// simulate link click
  document.body.appendChild(element); // Required for this to work in FireFox
  element.click();
}

But each time I got a CSP error :

Content-Security-Policy : Les paramètres de la page ont empêché le chargement d’une ressource (frame-src) à l’adresse blob:http://localhost:3000/c967a477-517c-4a45-b661-0db72d23a37a car elle enfreint la directive suivante : « frame-src 'self' https://{environmentid}.live.dynatrace.com https://sso.dynatrace.com https://chat-one.dynatrace.com https://dev.access-approval.internal.dynatracelabs.com https://hardening.access-approval.internal.dynatracelabs.com https://access-approval.internal.dynatrace.com http://localhost:3000 »

I tried to change the CSP rules, but it didn’t work and according to this it might not be possible to change frame-src.

Is there an alternative approach to allow file downloads without running into CSP restrictions?

Hi Auriane,

I’ll update you soon with a better answer. For now, can you try to do a workaround which is to create an iframe with a download link instead of having it in the main document:

Some explanation: CSP frame-src blocked on Firefox for blob on Embedded app · Issue #11 · Shopify/shopify-app-bridge · GitHub

function downloadBlobFile(file) {
const blobUrl = URL.createObjectURL(file);

const iframe = document.createElement('iframe');

iframe.style.display = 'none';

iframe.addEventListener('load', () => {

const a = iframe.contentDocument.createElement('a');

a.href = blobUrl;
a.download = file.name;

iframe.contentDocument.body.appendChild(a);

a.click();
})

document.body.appendChild(iframe);

setTimeout(() => {
document.body.removeChild(iframe);
}, 1000);
}

const file = new File(['Hello, world!'], "aaa.json",{type: 'application/json'});
downloadBlobFile(file);

It works !

Thank you