Created
March 2, 2023 11:59
-
-
Save ivanhoe011/95dd4ca8dbfa5daac85e6fcf1aa829e6 to your computer and use it in GitHub Desktop.
Get html from clipboard with js
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
document | |
// can be any element that knows how to recieve the paste event | |
.getElementById('someElement') | |
// add event listener | |
.addEventListener('paste', e => { | |
if (! e.clipboardData.types.includes('text/html')) { | |
// if there's no html on the clipboard ignore it | |
return; | |
} | |
// use <template> to convert the html string to a DOM tree | |
const tpl = document.createElement('template'); | |
// get clipboard content (always trim to avoid creating empty text nodes) | |
tpl.innerHTML = e.clipboardData.getData('text/html').trim(); | |
// get html as DOM elements | |
const html = tpl.content.children; | |
// do something with it... | |
// if you don't want to paste the text version of the clipboard, prevent the default action | |
e.preventDefault(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment