How to copy text to the clipboard with JavaScript?

To copy text to the clipboard in JavaScript, we can use both modern and legacy approaches. The modern navigator.clipboard API is recommended, while the older document.execCommand() method provides fallback support.

Modern Approach: Using navigator.clipboard API

The navigator.clipboard.writeText() method is the modern standard for copying text. It returns a Promise and works asynchronously.

<!DOCTYPE html>
<html>
<head>
    <style>
        button {
            border: none;
            outline: none;
            background-color: rgb(191, 187, 255);
            color: black;
            font-weight: bold;
            padding: 10px;
            margin: 5px;
        }
        input {
            padding: 10px;
            margin: 5px;
            width: 200px;
        }
    </style>
</head>
<body>
    <h2>Modern Clipboard API</h2>
    <input type="text" value="Hello World!" id="textInput1" />
    <button onclick="copyWithModernAPI()">Copy Text</button>
    
    <script>
        function copyWithModernAPI() {
            const textInput = document.getElementById('textInput1');
            navigator.clipboard.writeText(textInput.value).then(() => {
                console.log('Text copied successfully!');
                alert('Copied: ' + textInput.value);
            }).catch(err => {
                console.error('Failed to copy: ', err);
            });
        }
    </script>
</body>
</html>

Legacy Approach: Using document.execCommand()

The older method uses select(), setSelectionRange(), and document.execCommand('copy'). This approach requires selecting the text first.

<!DOCTYPE html>
<html>
<head>
    <style>
        button {
            border: none;
            outline: none;
            background-color: rgb(255, 191, 191);
            color: black;
            font-weight: bold;
            padding: 10px;
            margin: 5px;
        }
        input {
            padding: 10px;
            margin: 5px;
            width: 200px;
        }
    </style>
</head>
<body>
    <h2>Legacy execCommand Method</h2>
    <input type="text" value="Hello World!" id="textInput2" />
    <button onclick="copyWithExecCommand()">Copy Text</button>
    
    <script>
        function copyWithExecCommand() {
            const copyText = document.getElementById('textInput2');
            copyText.select();
            copyText.setSelectionRange(0, 99999); // For mobile devices
            document.execCommand('copy');
            console.log('Text copied using execCommand');
            alert('Copied: ' + copyText.value);
        }
    </script>
</body>
</html>

Complete Example with Fallback

A robust solution that tries the modern API first, then falls back to the legacy method:

<!DOCTYPE html>
<html>
<head>
    <style>
        .container {
            margin: 20px;
            padding: 20px;
            border: 1px solid #ccc;
        }
        button {
            border: none;
            outline: none;
            background-color: rgb(191, 255, 191);
            color: black;
            font-weight: bold;
            padding: 10px;
            margin: 5px;
        }
        input {
            padding: 10px;
            margin: 5px;
            width: 250px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Universal Clipboard Copy</h2>
        <input type="text" value="Copy this text!" id="universalInput" />
        <button onclick="copyTextUniversal()">Copy Text</button>
        <p id="status"></p>
    </div>
    
    <script>
        function copyTextUniversal() {
            const textInput = document.getElementById('universalInput');
            const statusEl = document.getElementById('status');
            
            // Try modern API first
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(textInput.value).then(() => {
                    statusEl.textContent = 'Copied using modern API: ' + textInput.value;
                }).catch(() => {
                    fallbackCopy();
                });
            } else {
                fallbackCopy();
            }
            
            function fallbackCopy() {
                textInput.select();
                textInput.setSelectionRange(0, 99999);
                const success = document.execCommand('copy');
                if (success) {
                    statusEl.textContent = 'Copied using fallback method: ' + textInput.value;
                } else {
                    statusEl.textContent = 'Copy failed!';
                }
            }
        }
    </script>
</body>
</html>

Comparison

Method Browser Support Security Requirements Status
navigator.clipboard Modern browsers HTTPS required Recommended
document.execCommand() All browsers User interaction required Deprecated but functional

Key Points

  • The navigator.clipboard API requires HTTPS for security
  • setSelectionRange(0, 99999) ensures mobile device compatibility
  • Always include fallback support for older browsers
  • Both methods require user interaction (button click) to work

Conclusion

Use the modern navigator.clipboard.writeText() API when possible, with document.execCommand('copy') as a fallback. This approach ensures maximum browser compatibility and provides a smooth user experience across all devices.

Updated on: 2026-03-15T23:18:59+05:30

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements