From d83cd45b6f0b85f477fa583777122f295c38dc2c Mon Sep 17 00:00:00 2001 From: Nicolas Gallagher Date: Sun, 23 Apr 2017 13:36:38 -0700 Subject: [PATCH] [fix] Clipboard browser support Safari 10.3 supports copying (but apparently not from inputs) --- src/apis/Clipboard/index.js | 34 +++++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/src/apis/Clipboard/index.js b/src/apis/Clipboard/index.js index 70c7d6a2..2efa5e50 100644 --- a/src/apis/Clipboard/index.js +++ b/src/apis/Clipboard/index.js @@ -1,19 +1,43 @@ +/* global window */ + class Clipboard { + static isSupported() { + return ( + typeof document.queryCommandSupported === 'function' && document.queryCommandSupported('copy') + ); + } + static getString() { return Promise.resolve(''); } static setString(text) { let success = false; - const textField = document.createElement('textarea'); - textField.innerText = text; - document.body.appendChild(textField); - textField.select(); + + // add the text to a hidden node + const node = document.createElement('span'); + node.textContent = text; + node.style.position = 'absolute'; + node.style.opacity = '0'; + document.body.appendChild(node); + + // select the text + const selection = window.getSelection(); + selection.removeAllRanges(); + const range = document.createRange(); + range.selectNodeContents(node); + selection.addRange(range); + + // attempt to copy try { document.execCommand('copy'); success = true; } catch (e) {} - document.body.removeChild(textField); + + // remove selection and node + selection.removeAllRanges(); + document.body.removeChild(node); + return success; } }