Skip to content

Instantly share code, notes, and snippets.

Created September 11, 2019 18:32
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
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.pathname
// just prior to copying, temporarily change the input value to the
// to be copied url
inputHTMLElement.value = copyUrl
// select the input value
// Required for iOS
// See also
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.setSelectionRange(0, 0)
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