Categories
JavaScript Answers

How to copy the current URL to the clipboard with JavaScript?

Spread the love

To copy the current URL to the clipboard with JavaScript, we can call navigator.clipboard.writeText with window.location.href.

For instance, we write:

<button>
  copy
</button>

to add a button.

Then we write:

const button = document.querySelector('button')
button.onclick = () => {
  navigator.clipboard.writeText(window.location.href);
}

We get the button with document.querySelector.

Then we set the button.onclick property to a function that calls navigator.clipboard.writeText with window.location.href.

window.location.href has the URL of the current page, so the URL will be copied to the clipboard with the copy button is clicked.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to copy the current URL to the clipboard with JavaScript?”

Hi John, thanks for that snippet 🙂

I’m a russian guy who lives in Mexico now 😀

you’ve made my life a bit easier 😉

Leave a Reply

Your email address will not be published. Required fields are marked *