cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Downloading blocked by CSP

Auriane
Visitor

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?

2 REPLIES 2

haris
Dynatrace Participant
Dynatrace Participant

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: https://github.com/Shopify/shopify-app-bridge/issues/11#issuecomment-710605337

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

Featured Posts