How to copy text to the clipboard in JavaScript?
Sep 18, 2025 am 03:50 AMThe writeText method of the Clipboard API can copy text to the clipboard, it needs to be called in security context and user interaction, supports modern browsers, and the old version can be downgraded by execCommand.
To copy text to the clipboard in JavaScript, you can use the Clipboard API , specifically the navigator.clipboard.writeText()
method. This is the modern and recommended approach.
Using the Clipboard API (Modern Method)
This method is asynchronous and returns a Promise. It works in most modern browsers but requires a secure context (HTTPS or localhost).
navigator.clipboard.writeText("Hello, world!").then(() => { console.log("Text copied to clipboard"); }).catch(err => { console.err("Failed to copy: ", err); });Because it returns a Promise, you can also use async/await :
async function copyText(text) { try { await navigator.clipboard.writeText(text); console.log("Copied!"); } catch (err) { console.error("Copy failed: ", err); } }Handling User Gesture Requirement
Browsers require clipboard access to be triggered by a user action, like a button click. You can attach the copy function to a click event:
document.getElementById("copyBtn").addEventListener("click", () => { navigator.clipboard.writeText("Text to copy").then(() => { alert("Copied!"); }).catch(err => { alert("Failed: " err); }); });Fallback for Older Browsers
For older browsers that don't support the Clipboard API, you can use document.execCommand('copy')
(deprecated but still functional in some environments).
Steps:
- Create a temporary
<textarea></textarea>
element - Set its value to the text you want to copy
- Append it to the DOM and select its content
- Run
document.execCommand('copy')
- Remove the temporary element
Check for navigator.clipboard
support first, then fall back if needed:
Basically just use the Clipboard API when possible, and provide a fallback only if you need to support older environments. Keep in mind permissions and user interaction requirements.
The above is the detailed content of How to copy text to the clipboard in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Check your keyboard If keyboard shortcuts don't work, there may be an issue with the keyboard itself. Make sure it is plugged in correctly and recognized by your PC. Have a laptop keyboard giving you trouble? If you have an extra keyboard, plug it in and see if it works. If so, it may be an issue with the keyboard itself. Using a wireless keyboard? Follow the manufacturer's instructions to re-pair. You should also check any cables for damage and make sure the keys are free of debris and pressed properly. For more information, check out these fixes for broken Windows 11 keyboard. Using the Print Screen Key If you desperately need a screenshot and don't have time to troubleshoot, you can use the workaround first. For a full photo of the desktop, click

Copying has always been a great way to save and share files. It allows you to create manual backups, perform simple transfers, and even make modifications that might damage the original file if not copied. However, this can sometimes be difficult if you have problems trying to use the clipboard on your Windows PC. Some Windows 11 users have recently been unable to use copy-paste on their systems. This issue can occur due to a number of reasons and if you are in the same boat, then you can fix it on your PC. How to Fix Copy-Paste on Windows 11 Since there are many issues that can cause copy-paste to malfunction on Windows, we have listed the most common solutions to fix this problem below. We recommend that you start with the first

Where is the clipboard on iPhone? Since iOS is a closed ecosystem, the clipboard is an internal feature stored in virtual memory. By default, users cannot view the clipboard contents or edit them in any way. However, there are some ways to access the clipboard on iPhone. You can paste the clipboard into the Notes application (or any other text editor) and keep multiple copies of the clipboard there, editing them as needed. Alternatively, you can use the Shortcuts app to create a shortcut that displays the clipboard. Finally, you can use a third-party application such as Paste. How to access the clipboard on iPhone? Whether you prefer to use the built-in Notes app,

View macOS Clipboard History from Finder When you copy anything on your Mac (text, images, files, URLs, etc.), it goes to the Clipboard. Here's how to see what was last copied on your Mac. Go to Finder and click "Edit" in the menu bar. Click "Show Clipboard". This will open a window showing the contents of the macOS clipboard. Get Clipboard History Containing Multiple Items in Mac Of course, native Mac Clipboard History isn't the most versatile tool you can have. It only shows the last thing you copied, so if you want to copy multiple things at once and then paste them all together, you simply can't do that. However, if you are looking for

Where are clippings and screenshots in Windows 11? This is a question we get from some of our readers who may have just installed a new operating system or used a snipping tool for the first time. This tool is designed to capture any or all parts of your computer screen. To put things in context, the PrintScreen key will take a complete snapshot of your screen, but the SnippingTool can be adjusted to grab just the area you like. Where are screenshots and screenshots on Windows 10/11? By default, clippings and screenshots are saved to your computer's clipboard. This means that to retrieve them you simply paste them into your desired application such as Microsoft Paint, Photo

<h2>Using Clipboard History on Windows 11</h2><p>You can still use <strong>right-click>copy</strong> and <strong>right-click> Paste </strong> or use <strong>Ctrl+C</strong&

You no longer need to manually save screenshots captured using the Snipping Tool in Windows 11. In addition to being copied to the clipboard, they will be automatically saved in PNG format in the "Screenshots" folder under "My Pictures" in version 11.2209.2.0 of the app forward. Here's how you can enable or disable this behavior. Snipping Tool in Windows 11 So far, using the Snipping Tool, when you use the shortcut keys Win+Shift+S and capture a screenshot. It will automatically copy to your clipboard and you can paste it into Paint or other image editor, or you can open SnippingTool to mark up and share. However, the app severely lacks auto-save functionality

Copy and Paste Text Between Android and Windows 11 Note: For this article, we are using Windows 11, but the process is almost the same on Windows 10. First, you need to enable the clipboard history feature if you haven't already. You can enable it using the following steps: Click Start or press the Windows key to launch the Start menu and click Settings. When Settings opens, click System on the left. Scroll down to the list on the right and select the Clipboard option from the menu. Toggle the Clipboard History option On. In the same section, enable cross-device sync and select Automatically sync text I copy. Install Microsoft on Android
