Skip to content

Instantly share code, notes, and snippets.

@wilsonpage
Created August 9, 2019 13:21
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilsonpage/6f15d9b173584195eaa5dee42215bd81 to your computer and use it in GitHub Desktop.
Save wilsonpage/6f15d9b173584195eaa5dee42215bd81 to your computer and use it in GitHub Desktop.
iOS Safari copy to clipboard
const fallback = (text) => {
const isIos = navigator.userAgent.match(/ipad|iphone/i);
const textarea = document.createElement('textarea');
// create textarea
textarea.value = text;
// ios will zoom in on the input if the font-size is < 16px
textarea.style.fontSize = '20px';
document.body.appendChild(textarea);
// select text
if (isIos) {
const range = document.createRange();
range.selectNodeContents(textarea);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
textarea.setSelectionRange(0, 999999);
} else {
textarea.select();
}
// copy selection
document.execCommand('copy');
// cleanup
document.body.removeChild(textarea);
};
export default (text) => {
if (!navigator.clipboard) {
fallback(text);
return;
}
navigator.clipboard.writeText(text);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment