- How to Copy Text to Clipboard using JavaScript?
- Interact with the clipboard
- Writing to the clipboard
- Using the Clipboard API
- Using execCommand()
- Browser-specific considerations
- Reading from the clipboard
- Using the Clipboard API
- Using execCommand()
- Browser-specific considerations
- Browser compatibility
- api.Clipboard
- webextensions.api.clipboard
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- How TO — Copy Text to Clipboard
- Copy Text to Clipboard
- Example
- Example
- Display Copied Text in a Tooltip
- Example
How to Copy Text to Clipboard using JavaScript?
am going to open the folder in VScode you can use your favorite editor which you are comfortable with.
open index.html and paste the following code.
lang="en"> charset="UTF-8" /> http-equiv="X-UA-Compatible" content="IE=edge" /> name="viewport" content="width=device-width, initial-scale=1.0" /> Copy Text To Clipboard rel="stylesheet" href="style.css" /> class="container"> class="wrapper"> type="text" name="text" id="text" placeholder="Type any text and click copy" autocomplete="no" /> id="btn" class="btn">Click to Copy /> /> cols="30" rows="5"> src="script.js">
In the above HTML file we have:
- Linked our style.css
- Linked the script.js
- Created a form with input box(for the user to type the text to be copied), a button which will execute our function on click, textarea (not needed though) I will use this to paste the copied text so as to show you!
lets style the above compnents;
Open style.css and paste the following code
* margin: 0; padding: 0; box-sizing: border-box; > main height: 100vh; width: 100%; background-color: #eee; display: flex; justify-content: center; align-items: center; > .wrapper background: #fff; width: 400px; height: 200px; box-shadow: 5px 5px 15px 10px rgba(0, 0, 0, 0.2), 5px 5px 15px 10px rgba(255, 255, 255, 0.5); border-radius: 8px; display: flex; justify-content: center; align-items: center; > input#text padding: 5px 10px; font-size: 18px; > button#btn padding: 5px; font-size: 18px; border-radius: 6px; border: none; outline: none; cursor: pointer; background: transparent; color: #4b4949; box-shadow: 1px 1px 2px 2px rgba(0, 0, 0, 0.2); transition: all 0.3s ease-in-out; > button#btn:hover background-color: #76daf6; box-shadow: 5px 5px 2px 3px rgba(0, 0, 0, 0.3); >
I will not go deep into the styles above.
You can style yours the way you like.
Our webpage should look something like below:
Now lets begin to code our javascript
open script.js and copy the following code:
const btn = document.getElementById("btn"); btn.addEventListener("click", copyText); function copyText(e) e.preventDefault(); const text = document.getElementById("text"); text.select(); document.execCommand("copy"); >
Line 1 we have grabbed our button
Line 2 we add click event to the button which will trigger a function copyText
lets understand our function now.
we have used e.preventDefault() to prevent the default behaviour of the form.
We grab our textbox, and used javascript method select() to select the text typed inside the textbox
Now we come to the magical line of code
When an HTML document has been switched to designMode, its document object exposes an execCommand method to run commands that manipulate the current editable region, such as form inputs or contentEditable elements.
copy
Copies the current selection to the clipboard.
The above line of code, copies the selected text to the clipboard.
So we have reached end of the mini tutorial. Hope you have enjoyed it.
If you have liked the post or it was something new that you have learned today please do not forget to give a like. And if you have not already please give a follow to receive notifications whenever there is a new post.
Here are the links to my previous post please have a look:
Interact with the clipboard
Working with the clipboard in extensions is transitioning from the Web API document.execCommand method (which is deprecated) to the navigator.clipboard method.
Note: The navigator.clipboard API is a recent addition to the specification and may not be fully implemented in all browsers. This article describes some limitations, but be sure to review the compatibility tables for each method before using them to ensure that the API supports your needs.
The difference between the two APIs is that document.execCommand this is analogous to the keyboard copy, cut, and paste actions – exchanging data between a webpage and clipboard – whereas navigator.clipboard writes and reads arbitrary data to and from the clipboard.
navigator.clipboard provide separate methods to read or write:
- work with images use browser.clipboard.setImageData() to write images to the clipboard and document.execCommand(«paste») to paste images to a webpage.
- write rich content (such as, HTML, rich text including images, etc.) to the clipboard, use document.execCommand(«copy») or document.execCommand(«cut») . Then, either navigator.clipboard.read() (recommended) or document.execCommand(«paste») to read the content from the clipboard.
Writing to the clipboard
This section describes the options for writing data to the clipboard.
Using the Clipboard API
The Clipboard API writes arbitrary data to the clipboard from your extension. Using the API requires the permission «clipboardRead» or «clipboardWrite» in your manifest.json file. As the API is only available to Secure Contexts, it cannot be used from a content script running on http: -pages, only https: -pages.
For page scripts, the «clipboard-write» permission needs to be requested using the Web API navigator.permissions . You can check for that permission using navigator.permissions.query() :
.permissions.query( name: "clipboard-write" >).then((result) => if (result.state === "granted" || result.state === "prompt") /* write to the clipboard now */ > >);
Note: The clipboard-write permission name is not supported in Firefox, only Chromium browsers.
This function takes a string and writes it to the clipboard:
function updateClipboard(newClip) navigator.clipboard.writeText(newClip).then( () => /* clipboard successfully set */ >, () => /* clipboard write failed */ >, ); >
Using execCommand()
The «cut» and «copy» commands of the document.execCommand() method are used to replace the clipboard’s content with the selected material. These commands can be used without any special permission in short-lived event handlers for a user action (for example, a click handler).
For example, suppose you’ve got a popup that includes the following HTML:
input id="input" type="text" /> button id="copy">Copybutton>
To make the «copy» button copy the contents of the element, you can use code like this:
function copy() let copyText = document.querySelector("#input"); copyText.select(); document.execCommand("copy"); > document.querySelector("#copy").addEventListener("click", copy);
Because the execCommand() call is inside a click event handler, you don’t need any special permissions.
However, let’s say that instead you trigger the copy from an alarm:
function copy() let copyText = document.querySelector("#input"); copyText.select(); document.execCommand("copy"); > browser.alarms.create( delayInMinutes: 0.1, >); browser.alarms.onAlarm.addListener(copy);
Depending on the browser, this may not work. On Firefox, it will not work, and you’ll see a message like this in your console:
document.execCommand(‘cut’/’copy’) was denied because it was not called from inside a short running user-generated event handler.
To enable this use case, you need to ask for the «clipboardWrite» permission. So: «clipboardWrite» enables you to write to the clipboard outside a short-lived event handler for a user action.
Note: document.execCommand() does not work on input fields of type=»hidden» , with the HTML5 attribute «hidden» , or any matching CSS rule using «display: none;» . So, to add a «copy to clipboard» button to a span , div , or p tag, you need to use a workaround, such as setting the input’s position to absolute and moving it out of the viewport.
Browser-specific considerations
The clipboard and other APIs involved here are evolving rapidly, so there are variations among browsers in how they work.
- You don’t need «clipboardWrite» , even to write to the clipboard outside a user-generated event handler.
See the browser compatibility tables for more information.
Reading from the clipboard
This section describes the options for reading or pasting data from the clipboard.
Using the Clipboard API
The Clipboard API’s navigator.clipboard.readText() and navigator.clipboard.read() methods let you read arbitrary text or binary data from the clipboard in secure contexts. This lets you access the data in the clipboard without pasting it into an editable element.
Once you have the «clipboard-read» permission from the Permissions API, you can read from the clipboard easily. For example, this snippet of code fetches the text from the clipboard and replaces the contents of the element with the ID «outbox» with that text.
.clipboard .readText() .then((clipText) => (document.getElementById("outbox").innerText = clipText));
Using execCommand()
To use document.execCommand(«paste») your extension needs the «clipboardRead» permission. This is the case even if you’re using the «paste» command from within a user-generated event handler, such as click or keypress .
Consider HTML that includes something like this:
textarea id="output">textarea> button id="paste">Pastebutton>
function paste() let pasteText = document.querySelector("#output"); pasteText.focus(); document.execCommand("paste"); console.log(pasteText.textContent); > document.querySelector("#paste").addEventListener("click", paste);
Browser-specific considerations
Firefox supports the «clipboardRead» permission from version 54 but only supports pasting into elements in content editable mode, which for content scripts only works with a . For background scripts, any element can be set to content editable mode.
Browser compatibility
api.Clipboard
BCD tables only load in the browser
webextensions.api.clipboard
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 11, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
How TO — Copy Text to Clipboard
Learn how to copy text to the clipboard with JavaScript.
Click on the button to copy the text from the text field.
Copy Text to Clipboard
Step 1) Add HTML:
Example
Step 2) Add JavaScript:
Example
function myFunction() <
// Get the text field
var copyText = document.getElementById(«myInput»);
// Select the text field
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(copyText.value);
// Alert the copied text
alert(«Copied the text: » + copyText.value);
>
Display Copied Text in a Tooltip
Example
.tooltip <
position: relative;
display: inline-block;
>
.tooltip .tooltiptext visibility: hidden;
width: 140px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%;
left: 50%;
margin-left: -75px;
opacity: 0;
transition: opacity 0.3s;
>
.tooltip .tooltiptext::after content: «»;
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
>
.tooltip:hover .tooltiptext visibility: visible;
opacity: 1;
>