unicode: copy to clipboard using execCommand
authorMischa POSLAWSKY <perl@shiar.org>
Mon, 26 Oct 2015 22:16:09 +0000 (23:16 +0100)
committerMischa POSLAWSKY <perl@shiar.org>
Mon, 26 Oct 2015 22:46:41 +0000 (23:46 +0100)
Fallback via temporary textarea for modern browsers (chrome 43+, ff 41+).

Code adapted from:
<http://stackoverflow.com/questions/400212/copy-in-js#answer-30810322>

clipboard.js

index cbf43d671c5bed78f96ffb8801c1f11fb6e0da7d..8ef21d1e82a3172d47f4ebc58cad5d860d06592d 100644 (file)
@@ -5,29 +5,31 @@ function clipboardcopy(val) {
                return window.clipboardData.setData('text', 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 {
                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);
        }
 }
 
        }
 }