Skip to content

Commit

Permalink
feat: add downloadURL function
Browse files Browse the repository at this point in the history
  • Loading branch information
MilosPaunovic committed Jun 29, 2024
1 parent 9e5acac commit 8518ace
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
// modules/numbers

// modules/strings
export * from './modules/strings/uniqueIdentifier'

// modules/various
export * from './modules/various/downloadURL'
43 changes: 43 additions & 0 deletions src/modules/various/downloadURL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Downloads a file from the specified URL with the given filename.
*
* @param {string} url - The URL of the file to download.
* @param {string} [filename] - The name to give the downloaded file.
*
* @example
* downloadURL('https://example.com/file.pdf', 'myfile.pdf');
*
* @example
* downloadURL('https://example.com/image.png'); // Filename will be 'download'
*/
export function downloadURL(url: string, filename: string = 'download'): void {
try {
// Validate URL
let validatedURL
try {
validatedURL = new URL(url)
}
catch (_) {
throw new Error('Invalid URL provided')
}

// Create a temporary link element
const link: HTMLAnchorElement = document.createElement('a')
link.href = validatedURL.toString()
link.setAttribute('download', filename)
link.setAttribute('target', '_blank')

// Append the link to the body, trigger the download, then remove the link
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
catch (error: unknown) {
if (error instanceof Error) {
console.error('Error downloading the file:', error.message)
}
else {
console.error('An unknown error occurred')
}
}
}

0 comments on commit 8518ace

Please sign in to comment.