Skip to content

Instantly share code, notes, and snippets.

@orjan
Created November 27, 2021 16:16
Show Gist options
  • Save orjan/1f303eb97faab16b7e64d0e1b3adc36f to your computer and use it in GitHub Desktop.
Save orjan/1f303eb97faab16b7e64d0e1b3adc36f to your computer and use it in GitHub Desktop.
Read and parse the clipboard
<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