08 Nov 2024 02:05 PM - edited 08 Nov 2024 02:06 PM
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?
Solved! Go to Solution.
11 Nov 2024 12:42 PM - edited 11 Nov 2024 12:44 PM
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);
12 Nov 2024 09:05 AM
It works !
Thank you