Skip to content

Instantly share code, notes, and snippets.

@rproenca
Last active May 22, 2026 13:16
Show Gist options
  • Select an option

  • Save rproenca/64781c6a1329b48a455b645d361a9aa3 to your computer and use it in GitHub Desktop.

Select an option

Save rproenca/64781c6a1329b48a455b645d361a9aa3 to your computer and use it in GitHub Desktop.
Copy text to clipboard using Javascript. It works on Safari (iOS) and other browsers.
window.Clipboard = (function(window, document, navigator) {
var textArea,
copy;
function isOS() {
return navigator.userAgent.match(/ipad|iphone/i);
}
function createTextArea(text) {
textArea = document.createElement('textArea');
textArea.value = text;
document.body.appendChild(textArea);
}
function selectText() {
var range,
selection;
if (isOS()) {
range = document.createRange();
range.selectNodeContents(textArea);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textArea.setSelectionRange(0, 999999);
} else {
textArea.select();
}
}
function copyToClipboard() {
document.execCommand('copy');
document.body.removeChild(textArea);
}
copy = function(text) {
createTextArea(text);
selectText();
copyToClipboard();
};
return {
copy: copy
};
})(window, document, navigator);
Clipboard.copy('text to be copied');
@Benetos

Benetos commented Sep 22, 2019

Copy link
Copy Markdown

Is there a way to use this to copy multiple text boxes? From a form or something along those lines?

@SWei1234

SWei1234 commented Jan 7, 2021

Copy link
Copy Markdown

Looks like it's not working on safari 13...

@creeperyang

Copy link
Copy Markdown

@ppab

ppab commented Jul 22, 2021

Copy link
Copy Markdown

Thanks!

@stow1x

stow1x commented Aug 19, 2021

Copy link
Copy Markdown

That cool. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment