Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle potential CORS issues during file downloads #25556

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/libs/fileDownload/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import * as ApiUtils from '@libs/ApiUtils';
import tryResolveUrlFromApiRoot from '@libs/tryResolveUrlFromApiRoot';
import * as Link from '@userActions/Link';
import * as FileUtils from './FileUtils';

Expand All @@ -8,7 +10,15 @@ import * as FileUtils from './FileUtils';
* @returns {Promise}
*/
export default function fileDownload(url, fileName) {
return new Promise((resolve) => {
const resolvedUrl = tryResolveUrlFromApiRoot(url);
if (!resolvedUrl.startsWith(ApiUtils.getApiRoot())) {
// Different origin URLs might pose a CORS issue during direct downloads.
// Opening in a new tab avoids this limitation, letting the browser handle the download.
Link.openExternalLink(url);
return Promise.resolve();
}

return (
fetch(url)
.then((response) => response.blob())
.then((blob) => {
Expand All @@ -35,12 +45,8 @@ export default function fileDownload(url, fileName) {
// Clean up and remove the link
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
return resolve();
})
.catch(() => {
// file could not be downloaded, open sourceURL in new tab
Link.openExternalLink(url);
return resolve();
});
});
// file could not be downloaded, open sourceURL in new tab
.catch(() => Link.openExternalLink(url))
);
}
Loading