Skip to content

Instantly share code, notes, and snippets.

@tommedema
Created September 11, 2019 18:32
Show Gist options
  • Save tommedema/c99079f90e49f5e545feb2a50d594f6e to your computer and use it in GitHub Desktop.
Save tommedema/c99079f90e49f5e545feb2a50d594f6e to your computer and use it in GitHub Desktop.
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

Nice Code! It's working fine

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