Skip to content

Instantly share code, notes, and snippets.

@jaf7
Forked from lgarron/copyToClipboard.html
Created March 13, 2021 03:41
Show Gist options
  • Save jaf7/ade5ed5f594c44cd04e7d93bd1e3e461 to your computer and use it in GitHub Desktop.
Save jaf7/ade5ed5f594c44cd04e7d93bd1e3e461 to your computer and use it in GitHub Desktop.
Simple `navigator.clipboard.writeText()` polyfill.
<script>
// A minimal polyfill for `navigator.clipboard.writeText()` that works most of the time in most modern browsers.
// Note that:
// - In Edge, this may call `resolve()` even if copying failed.
// - In Safari, this may fail if there is nothing selected on the page.
// See https://github.com/lgarron/clipboard-polyfill for a more robust solution.
// License: public domain
function writeText(str) {
return new Promise(function(resolve, reject) {
var success = false;
function listener(e) {
e.clipboardData.setData("text/plain", str);
e.preventDefault();
success = true;
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
success ? resolve(): reject();
});
};
</script>
<button onclick="writeText(this.textContent)">Copy me!</button>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment