Created
October 20, 2016 04:10
-
-
Save sdiama/c7bd0259db09c687bd6d8214bd6e31bb to your computer and use it in GitHub Desktop.
Accessing The Clipboard With JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment