Categories
JavaScript Answers

How to get HTML from the clipboard in JavaScript?

Spread the love

Sometimes, we want to get HTML from the clipboard in JavaScript.

In this article, we’ll look at how to get HTML from the clipboard in JavaScript.

How to get HTML from the clipboard in JavaScript?

To get HTML from the clipboard in JavaScript, we can listen to the paste event.

For instance, we write:

document.addEventListener('paste', (e) => {
  const html = e.clipboardData.getData('text/html');
  console.log(html)
})

to call document.addEventListener with 'paste' and a callback that runs when we paste onto the page.

In the callback, we get the clipboard data with e.clipboardData.getData('text/html').

Now whenever we copy content from browser tabs and paste it onto the page, we should see the HTML code logged.

Conclusion

To get HTML from the clipboard in JavaScript, we can listen to the paste event.

By John Au-Yeung

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

Leave a Reply

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