Skip to content

Latest commit

 

History

History
44 lines (40 loc) · 1.41 KB

clipboard-api.md

File metadata and controls

44 lines (40 loc) · 1.41 KB
title tags references
Clipboard API
web
javascript

Complete example for text

let copyTrigger = document.getElementById('copy_body_button')
let copyContent = document.querySelector('main')

copyTrigger.addEventListener('click', () => {
	// Create a new clipboard item
	const item = new ClipboardItem({
		// The clipboard item can hold multiple formats
		// In this case we're encoding the body as HTML for use with CMD+V (paste)
		'text/html': new Blob([copyContent.innerHTML], {
			type: 'text/html',
		}),
		// And we're encoding a plaintext version for use with CMD+ALT+V (paste without formatting)
		'text/plain': new Blob([copyContent.innerText], {
			type: 'text/plain',
		}),
	})

	// Push it to the clipboard and handle success/failure signals
	navigator.clipboard.write([item]).then(
		function () {
			console.log('Async: Copying to clipboard was successful!')
		},
		function (err) {
			console.error('Async: Could not copy text: ', err)
		}
	)
})