Created
September 11, 2019 18:32
-
-
Save tommedema/c99079f90e49f5e545feb2a50d594f6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice Code! It's working fine