title: Javascript Clipboard API tags: web js clipboard h1: ## References * [Mozilla docs: Clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) * [Mozilla docs: Interact with clipboard](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard) ## Examples To copy to clipboard: ```js navigator.clipboard.writeText(newClip) ``` Or more fully (example from mozilla) ```js function updateClipboard(newClip) { navigator.clipboard.writeText(newClip).then( () => { /* clipboard successfully set */ }, () => { /* clipboard write failed */ }, ); } ``` To paste from clipboard (from mozilla docs): ```js navigator.clipboard .readText() .then((clipText) => (document.getElementById("outbox").innerText = clipText)); ``` ## Old School Method If not on https, then the clipboard API is not available. There is an old technique which still works. Often I have things on my LAN where I want to copy, and it is annoying to have to manually add machines to a Chrome whitelist (on each machine I use), and then put up with the resulting nagging about treating insecure sites as secure. ```js function docopy(text) { const textArea = document.createElement("textarea"); textArea.value = text; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { document.execCommand('copy'); } catch (err) { console.error('Unable to copy to clipboard', err); } document.body.removeChild(textArea); } ```