Created
November 27, 2021 16:16
-
-
Save orjan/1f303eb97faab16b7e64d0e1b3adc36f to your computer and use it in GitHub Desktop.
Read and parse the clipboard
This file contains hidden or 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
<html> | |
<head></head> | |
<body> | |
<h1>Clippy</h1> | |
<p class="editor"></p> | |
<fieldset> | |
<legend>Work order form</legend> | |
<label for="address">Address</label><br/> | |
<input type="text" id="address" /><br/> | |
<label for="city">City</label><br/> | |
<input type="text" id="city" /><br/> | |
</fieldset> | |
<button onclick="getClipboardContents();">Read from clipboard</button> | |
<script> | |
async function getClipboardContents() { | |
const clipboardItems = await navigator.clipboard.read(); | |
const parsedDocument = await getClipboardDocument(clipboardItems); | |
const data = parseDocument(parsedDocument); | |
document.getElementById("address").value = data.address; | |
document.getElementById("city").value = data.city; | |
} | |
async function getClipboardDocument(items) { | |
for (const clipboardItem of items) { | |
const blob = await clipboardItem.getType("text/html"); | |
const data = await blob.text(); | |
const parser = new DOMParser(); | |
return parser.parseFromString(data, "text/html"); | |
} | |
} | |
function parseDocument(document) { | |
const address = document.querySelector(".mb-0").childNodes[0].textContent; | |
const city = document.querySelector(".mb-0").childNodes[1].textContent; | |
return { | |
address, | |
city | |
} | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment