Skip to content

Instantly share code, notes, and snippets.

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.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

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