Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Copy to clipboard for Chrome and Firefox
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>copy to clipboard for chrome and firefox</title>
</head>
<body>
<button>copy</button>
<script>
function toClipoard(text) {
if ("clipboard" in navigator && typeof navigator.clipboard.writeText === "function") {
// Chrome
return navigator.clipboard.writeText(text)
.then(() => true)
.catch(() => false);
} else {
// Firefox
const input = document.createElement("input");
input.value = text;
input.style.position = "fixed";
input.style.top = "-2000px";
document.body.appendChild(input);
input.select();
try {
return Promise.resolve(document.execCommand("copy"))
.then(res => {
document.body.removeChild(input);
return res;
});
} catch (err) {
return Promise.resolve(false);
}
}
}
document.querySelector("button").addEventListener("click", _ => {
toClipoard("this is a test")
.then(res => console.log("copied", res));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment