Created
April 30, 2017 20:07
-
-
Save santaklouse/5e83c16cbe1bccf30f062b0dd33b8f90 to your computer and use it in GitHub Desktop.
JS copy To Clipboard (prevent coping/cutting programmatically)
This file contains 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
// Copies a string to the clipboard. Must be called from within an | |
// event handler such as click. May return false if it failed, but | |
// this is not always possible. Browser support for Chrome 43+, | |
// Firefox 42+, Safari 10+, Edge and IE 10+. | |
// IE: The clipboard feature may be disabled by an administrator. By | |
// default a prompt is shown the first time the clipboard is | |
// used (per session). | |
function copyToClipboard(text) { | |
if (window.clipboardData && window.clipboardData.setData) { | |
// IE specific code path to prevent textarea being shown while dialog is visible. | |
return clipboardData.setData("Text", text); | |
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) { | |
var textarea = document.createElement("textarea"); | |
textarea.textContent = text; | |
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge. | |
document.body.appendChild(textarea); | |
textarea.select(); | |
try { | |
return document.execCommand("copy"); // Security exception may be thrown by some browsers. | |
} catch (ex) { | |
console.warn("Copy to clipboard failed.", ex); | |
return false; | |
} finally { | |
document.body.removeChild(textarea); | |
} | |
} | |
} | |
var func = function(e) { | |
// e.clipboardData is initially empty, but we can set it to the | |
// data that we want copied onto the clipboard. | |
e.clipboardData.setData('text/plain', 'copy or cut is disabled!'); | |
e.clipboardData.setData('text/html', '<b>copy or cut is disabled!</b>'); | |
// This is necessary to prevent the current document selection from | |
// being written to the clipboard. | |
e.preventDefault(); | |
}; | |
// Overwrite what is being copied to the clipboard. | |
document.addEventListener('copy', func); | |
document.addEventListener('cut', func); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment