Accessing The Clipboard With JavaScript
var button = document.getElementById("copy-button"),
contentHolder = document.getElementById("content-holder");
button.addEventListener("click", function() {
// We will need a range object and a selection.var range = document.createRange(),
selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
// Make the range select the entire content of the contentHolder paragraph.
range.selectNodeContents(contentHolder);
// Add that range to the selection.
selection.addRange(range);
// Copy the selection to clipboard.document.execCommand('copy');// Clear selection if you want to.
selection.removeAllRanges();
}, false);
/*
* Modify Copied Text
*/
document.addEventListener('copy', function(e) {
// We need to prevent the default copy functionality,// otherwise it would just copy the selection as usual.
e.preventDefault();
// The copy event doesn't give us access to the clipboard data,// so we need to get the user selection via the Selection API.var selection = window.getSelection().toString();// Transform the selection in any way we want.// In this example we will escape HTML code.var escaped = escapeHTML(selection);// Place the transformed text in the clipboard.
e.clipboardData.setData('text/plain', escaped);
});