Skip to content

Instantly share code, notes, and snippets.

@aont
Last active October 18, 2024 02:04
Show Gist options
  • Save aont/7daffb999774e839dc2f96b525a29857 to your computer and use it in GitHub Desktop.
Save aont/7daffb999774e839dc2f96b525a29857 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Copy to Clipboard</title>
</head>
<body>
<script>
window.addEventListener('load', (event) => {
const buttonCopy = document.createElement("button");
buttonCopy.innerText = "Copy to Clipboard";
document.body.appendChild(buttonCopy);
buttonCopy.addEventListener("click", function (event) {
const div = document.createElement("div");
div.innerHTML = "This is <strong>HTML</strong> content";
document.body.appendChild(div);
try {
const range = document.createRange();
range.selectNodeContents(div)
// range.selectNode(div)
// range.setStart(div, 0);
// range.setEndAfter(div);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("copy");
} finally {
document.body.removeChild(div);
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment