From ef6460a4e9da4b5082fe908fa9ef489c7ed2d652 Mon Sep 17 00:00:00 2001 From: Mischa POSLAWSKY Date: Mon, 26 Oct 2015 23:16:09 +0100 Subject: [PATCH] unicode: copy to clipboard using execCommand Fallback via temporary textarea for modern browsers (chrome 43+, ff 41+). Code adapted from: --- clipboard.js | 42 ++++++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/clipboard.js b/clipboard.js index cbf43d6..8ef21d1 100644 --- a/clipboard.js +++ b/clipboard.js @@ -5,29 +5,31 @@ function clipboardcopy(val) { return window.clipboardData.setData('text', val); } - if (netscape && netscape.security) { - // request access to XPCOM api - try { - netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); - } - catch(e) { - if (copyhint) - alert('Cannot access clipboard.\nSet boolean signed.applets.codebase_principal_support in about:config'); - copyhint = false; - return false; - } + if (document.queryCommandSupported('copy')) { + var textArea = document.createElement('textarea'); - // use nsIClipboard interface + // minimise styling in case it is (briefly) rendered + textArea.style.position = 'fixed'; + textArea.style.top = 0; + textArea.style.left = 0; + textArea.style.width = '2em'; + textArea.style.height = '2em'; + textArea.style.padding = 0; + textArea.style.border = 'none'; + textArea.style.outline = 'none'; + textArea.style.boxShadow = 'none'; + textArea.style.background = 'transparent'; + + // temporarily add input field to copy text from + textArea.value = val; + document.body.appendChild(textArea); try { - Components.classes['@mozilla.org/widget/clipboardhelper;1'] - .getService(Components.interfaces.nsIClipboardHelper) - .copyString(val); - return true; - } - catch(e) { - alert('Copy failed'); - return false; + textArea.select(); + document.execCommand('copy'); + } catch (e) { + console.log('could not copy "'+val+'" to clipboard'); } + document.body.removeChild(textArea); } } -- 2.30.0