Stack Overflow: add a copy-code button
Adds a small "Copy" button to every code block that copies the whole content to the clipboard in one click.
Code to copy
/* Add a "Copy" button to every code block */
(function () {
function addButtons() {
document.querySelectorAll('.s-prose pre, .js-post-body pre').forEach(function (pre) {
if (pre.dataset.sofCopy) return;
pre.dataset.sofCopy = '1';
pre.style.position = 'relative';
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:6px;right:6px;font-size:11px;padding:2px 8px;cursor:pointer;border:1px solid #aaa;border-radius:4px;background:#fff;z-index:5;';
btn.addEventListener('click', function () {
var code = pre.querySelector('code') || pre;
navigator.clipboard.writeText(code.innerText).then(function () {
btn.textContent = 'Copied!';
setTimeout(function () { btn.textContent = 'Copy'; }, 1500);
});
});
pre.appendChild(btn);
});
}
addButtons();
new MutationObserver(addButtons).observe(document.body, { childList: true, subtree: true });
})();
How to use this example
- Copy the code with the button above.
- Install JustZix (2 minutes) and open the extension on the target page.
- Add a new rule matching that page.
- Paste the code into the rule's JavaScript panel and save — it runs on every page visit.
Rate this example
No ratings yet — be the first.