Browser troubleshooting
Handle clipboard access failures gracefully
Clipboard writes can require a secure context, browser permission, and a direct user interaction. Trigger copying from a visible control and provide a manual fallback if the operation fails.
Worked example
HTML example · save as example.html and open in a browser
<button type="button" id="copy">Copy sample</button>
<p id="status" role="status"></p>
<script>
document.querySelector('#copy').onclick = async () => {
try {
await navigator.clipboard.writeText('sample text');
document.querySelector('#status').textContent = 'Copied';
} catch {
document.querySelector('#status').textContent = 'Select and copy manually: sample text';
}
};
</script>How it works
The write occurs inside the click handler rather than automatically on page load. The status reports whether the operation succeeded instead of showing an optimistic confirmation first. The fallback preserves the text for a user who cannot grant access.
Limits and mistakes
Policies differ across browsers and embedded contexts. Do not read the clipboard unnecessarily while implementing a copy action. Feature detection alone cannot prove a write will be permitted; handle the rejected promise.
Check the result
Serve through HTTPS or an appropriate local secure context and click the button. Test a denied or unavailable clipboard path and confirm the manual text remains accessible.
Sources
Reference documentation for the behavior used in this guide: