2011-10-10 13 views
36

Estaba tratando de hacer "Copiar al portapapeles" trabajo en todos los navegadores, pero no tuve suerte.Copiar al portapapeles para todos los navegadores usando javascript

Estoy usando javascript y no quiero usar Zero Clipboard para hacer.

Háganos saber lo que está mal en mi código.

Gracias por su ayuda.

A continuación se muestra el código (actualmente mi código está trabajando sólo en el navegador IE): -

<script type="text/javascript"> 
function copyToClipboard(s) 
{ 
    if(window.clipboardData && clipboardData.setData) 
    { 
     clipboardData.setData("Text", s); 
    } 
    else 
    { 
     // You have to sign the code to enable this or allow the action in about:config by changing 
     user_pref("signed.applets.codebase_principal_support", true); 
     netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); 

     var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard); 
     if (!clip) return; 

     // create a transferable 
     var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable); 
     if (!trans) return; 

     // specify the data we wish to handle. Plaintext in this case. 
     trans.addDataFlavor('text/unicode'); 

     // To get the data from the transferable we need two new objects 
     var str = new Object(); 
     var len = new Object(); 

     var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString); 

     var copytext=meintext; 

     str.data=copytext; 

     trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]); 

     var clipid=Components.interfaces.nsIClipboard; 

     if (!clip) return false; 

     clip.setData(trans,null,clipid.kGlobalClipboard);  
    } 
} 
</script> 

<textarea id='testText' rows="10" cols="100">Enter your Sample text</textarea><br /> 
<button onclick="copyToClipboard(document.getElementById('testText').value);" >clipboard</button><br /><br /> 
<textarea rows="10" cols="100">Paste your text here</textarea><br /> 
+0

¿Duplicado de http://stackoverflow.com/questions/400212/how-to-copy-to-clipboard-in-javascript? –

+4

Como sé, no puedes usar js para acceder al portapapeles en Firefox de manera predeterminada. La única forma universal es flash, en lugar de js. – Rufus

+0

@Rufus: Pero en mi caso, tengo que prescindir de flash. –

Respuesta

5

Por razones de seguridad la mayoría de los navegadores no permiten modificar el portapapeles (excepto IE, por supuesto ...) .

La única forma de hacer que una función de copiar en portapapeles sea compatible con varios navegadores es usar Flash.

+0

Usando el evento 'copy' es posible establecer datos de texto. Si no usa funciones nativas, entonces seleccione algún texto oculto para copiar. –

10

Esto funciona en Firefox 3.6.x e IE:

function copyToClipboardCrossbrowser(s) {   
     s = document.getElementById(s).value;    

     if(window.clipboardData && clipboardData.setData) 
     { 
      clipboardData.setData("Text", s); 
     }   
     else 
     { 
      // You have to sign the code to enable this or allow the action in about:config by changing 
      //user_pref("signed.applets.codebase_principal_support", true); 
      netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); 

      var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard); 
      if (!clip) return; 

      // create a transferable 

      var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable); 
      if (!trans) return; 

      // specify the data we wish to handle. Plaintext in this case. 
      trans.addDataFlavor('text/unicode'); 

      // To get the data from the transferable we need two new objects 
      var str = new Object(); 
      var len = new Object(); 

      var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 

      str.data= s;   

      trans.setTransferData("text/unicode",str, str.data.length * 2); 

      var clipid=Components.interfaces.nsIClipboard;    
      if (!clip) return false; 
      clip.setData(trans,null,clipid.kGlobalClipboard);  
     } 
    } 
+2

¡Guau! ¡Esto funciona! Pero al invocar cosas como "Components.classes ['@ mozilla.org/widget/transferable;1']", ¿vamos al sitio de Mozilla? –

+0

Esto no funciona en las versiones recientes de Firefox, donde 'Componentes 'está en desuso. –

+12

! ¡Necesitamos algo universal para todos los navegadores! , navegadores de comics ... donde ya estas. ¿Van a dejar que IE los venza a ustedes en esto? – Oneezy

8

que pasó mucho tiempo en busca de una solución a este problema también. Esto es lo que he encontrado hasta ahora:

Si desea que sus usuarios puedan hacer clic en un botón y copiar texto, es posible que deba usar Flash.

Si desea que sus usuarios presionen Ctrl + C en cualquier lugar de la página, pero siempre copie xyz en el portapapeles, escribí una solución all-JS en YUI3 (aunque podría ser fácilmente portado a otros frameworks, o raw JS si te sientes particularmente aborrecedor de ti mismo).

Implica crear un cuadro de texto fuera de la pantalla que se resalta tan pronto como el usuario pulsa Ctrl/CMD. Cuando presionan 'C' poco después, copian el texto oculto. Si presionan 'V', se los redirige a un contenedor (de su elección) antes de que se dispare el evento de pegar.

Este método puede funcionar bien, porque mientras escuchas la tecla Ctrl/CMD en cualquier parte del cuerpo, los oyentes de selección 'A', 'C' o 'V' solo se adjuntan al cuadro de texto oculto (y no al todo el cuerpo). Tampoco tiene que romper las expectativas de los usuarios: ¡solo se te redirecciona al cuadro oculto si no tienes nada seleccionado para copiar de todos modos!

Esto es lo que tengo trabajando en mi sitio, pero la salida http://at.cg/js/clipboard.js para las actualizaciones si las hay:

YUI.add('clipboard', function(Y) { 


// Change this to the id of the text area you would like to always paste in to: 

pasteBox = Y.one('#pasteDIV'); 


// Make a hidden textbox somewhere off the page. 

Y.one('body').append('<input id="copyBox" type="text" name="result" style="position:fixed; top:-20%;" onkeyup="pasteBox.focus()">'); 
copyBox = Y.one('#copyBox'); 


// Key bindings for Ctrl+A, Ctrl+C, Ctrl+V, etc: 

// Catch Ctrl/Window/Apple keydown anywhere on the page. 
Y.on('key', function(e) { 
    copyData(); 
     // Uncomment below alert and remove keyCodes after 'down:' to figure out keyCodes for other buttons. 
     // alert(e.keyCode); 
     // }, 'body', 'down:', Y); 
}, 'body', 'down:91,224,17', Y); 

// Catch V - BUT ONLY WHEN PRESSED IN THE copyBox!!! 
Y.on('key', function(e) { 
    // Oh no! The user wants to paste, but their about to paste into the hidden #copyBox!! 
    // Luckily, pastes happen on keyPress (which is why if you hold down the V you get lots of pastes), and we caught the V on keyDown (before keyPress). 
    // Thus, if we're quick, we can redirect the user to the right box and they can unload their paste into the appropriate container. phew. 
    pasteBox.select(); 
}, '#copyBox', 'down:86', Y); 

// Catch A - BUT ONLY WHEN PRESSED IN THE copyBox!!! 
Y.on('key', function(e) { 
    // User wants to select all - but he/she is in the hidden #copyBox! That wont do.. select the pasteBox instead (which is probably where they wanted to be). 
    pasteBox.select(); 
}, '#copyBox', 'down:65', Y); 



// What to do when keybindings are fired: 

// User has pressed Ctrl/Meta, and is probably about to press A,C or V. If they've got nothing selected, or have selected what you want them to copy, redirect to the hidden copyBox! 
function copyData() { 
    var txt = ''; 
    // props to Sabarinathan Arthanari for sharing with the world how to get the selected text on a page, cheers mate! 
     if (window.getSelection) { txt = window.getSelection(); } 
     else if (document.getSelection) { txt = document.getSelection(); } 
     else if (document.selection) { txt = document.selection.createRange().text; } 
     else alert('Something went wrong and I have no idea why - please contact me with your browser type (Firefox, Safari, etc) and what you tried to copy and I will fix this immediately!'); 

    // If the user has nothing selected after pressing Ctrl/Meta, they might want to copy what you want them to copy. 
     if(txt=='') { 
       copyBox.select(); 
     } 
    // They also might have manually selected what you wanted them to copy! How unnecessary! Maybe now is the time to tell them how silly they are..?! 
     else if (txt == copyBox.get('value')) { 
     alert('This site uses advanced copy/paste technology, possibly from the future.\n \nYou do not need to select things manually - just press Ctrl+C! \n \n(Ctrl+V will always paste to the main box too.)'); 
       copyBox.select(); 
     } else { 
       // They also might have selected something completely different! If so, let them. It's only fair. 
     } 
} 
}); 

Esperanza alguien encuentra este útil:]

+0

¿Qué pasa si el usuario usa el mouse para copiar al portapapeles? Exigir la tecla Ctrl/Cmd parece frágil. – Wolverine

Cuestiones relacionadas