Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const copyUrlToClipboard = (inputHTMLElement) => {
// the actual, to be copied url
const copyUrl = window.location.href
// the pretty url to display (without schema)
// this should be the default value of the input on instantiation
const displayUrl = window.location.host + window.location.pathname
// just prior to copying, temporarily change the input value to the
// to be copied url
inputHTMLElement.value = copyUrl
// select the input value
inputHTMLElement.select()
// Required for iOS
// See also https://stackoverflow.com/a/54966926/45974
inputHTMLElement.setSelectionRange(0, inputHTMLElement.value.length)
// Copy input value
try {
if (!document.execCommand('copy')) {
throw new Error(`failed to execute copy command`)
}
}
catch (e) {
console.log('Warning! Could not copy to clipboard.', e)
}
// Restore the pretty display url
inputHTMLElement.value = displayUrl
// Deselect the input
inputHTMLElement.focus()
inputHTMLElement.setSelectionRange(0, 0)
}
@Gulshanaggarwal
Copy link

Gulshanaggarwal commented May 4, 2021

Nice Code! It's working fine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment