Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Last active November 25, 2021 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangpin34/5d488ced7aff3c57aba87a1ed4e9ecaf to your computer and use it in GitHub Desktop.
Save wangpin34/5d488ced7aff3c57aba87a1ed4e9ecaf to your computer and use it in GitHub Desktop.
download, copy, select, etc
function download(text: string, name: string, type: string) {
var a = document.createElement('a')
a.style.display = "block";
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function copyToClipboard(object: string | HTMLElement, withStyling = false) {
const clipboard = window.navigator.clipboard
/*
* fallback to older browsers (including Safari)
* if clipboard API not supported
*/
if (!clipboard || typeof clipboard.writeText !== `function`) {
const sel = window.getSelection()
sel?.removeAllRanges()
if (typeof object === 'string' || withStyling === false) {
const textarea = document.createElement(`textarea`)
textarea.value = typeof object === 'string' ? object : object.innerText
textarea.setAttribute(`readonly`, String(true))
textarea.setAttribute(`contenteditable`, String(true))
textarea.style.position = `absolute`
textarea.style.left = `-9999px`
document.body.appendChild(textarea)
textarea.select()
textarea.setSelectionRange(0, textarea.value.length)
document.execCommand(`copy`)
document.body.removeChild(textarea)
} else {
const range = document.createRange()
range.selectNode(object as HTMLElement)
sel?.addRange(range)
document.execCommand(`copy`)
return Promise.resolve(true)
}
return Promise.resolve(true)
}
return clipboard.writeText(typeof object === 'string' ? (object as string) : (object as HTMLElement).innerHTML)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment