Skip to content
This repository has been archived by the owner on Jul 6, 2023. It is now read-only.

Commit

Permalink
fix(clipboard): add legacy fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
ttshivers committed Sep 18, 2020
1 parent c804844 commit 628e6e5
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion src/mixins/clipboard.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,56 @@
const cssText = 'position:fixed;pointer-events:none;z-index:-9999;opacity:0;';

const isString = (s) => typeof (s) === 'string' || s instanceof String;

const legacyCopy = (text) => {
const value = isString(text)
? text
: JSON.stringify(text);

const textarea = document.createElement('textarea');

textarea.value = value;
textarea.setAttribute('readonly', '');
textarea.style.cssText = cssText;

document.body.appendChild(textarea);

if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
textarea.contentEditable = true;
textarea.readOnly = true;

const range = document.createRange();

range.selectNodeContents(textarea);

const selection = window.getSelection();

selection.removeAllRanges();
selection.addRange(range);
textarea.setSelectionRange(0, 999999);
} else {
textarea.select();
}

try {
document.execCommand('copy');
} finally {
document.body.removeChild(textarea);
}
};

export default {
methods: {
async copyToClipboard(text) {
await navigator.clipboard.writeText(text);
try {
// The clipboard API can only be used in secure contexts, so fall back to legacy method if
// this fails
await navigator.clipboard.writeText(text);
} catch (e) {
console.warn(e);
}

legacyCopy(text);
await this.$store.dispatch('DISPLAY_NOTIFICATION', {
text: 'Copied to clipboard',
color: 'success',
Expand Down

0 comments on commit 628e6e5

Please sign in to comment.