i

Get the Alt Text of Copied Images with the Clipboard API

I was doomscrolling on Twitter the other night and saw this tweet from @FakeUnicode:

I had no idea this was possible! I might not be @TwitterSupport, but I did recently add alt text support to Discord. Wiring this up in Discord was pretty easy - we're iterating on how to inform users we've prefilled image alt text from their clipboard, but the code to retrieve and set the data is pretty simple.

// Simplified function
function handleClipboardEvent(event) {
	const file = event.clipboardData.files[0];
	let altText = null;
 
	// Find associated HTML
	if (event.clipboardData.types.includes("text/html")) {
		// Safely parse HTML and extract alt text
		const parser = new DOMParser().parseFromString(
			event.clipboardData.getData("text/html"),
			"text/html",
		);
 
		// All your favorite web APIs work!
		altText = parser.documentElement.querySelector("img")?.alt;
	}
 
	return {
		file,
		altText,
	};
}

If we're successful in finding a good UX for this, hopefully it will ship in Discord soon. I learned a lot from @FakeUnicode's tweet, and thought I'd share how I used the information in a complete function so others could try and do the same in their projects!