简体   繁体   中英

How to add formatted text to your clipboard using Javascript

I need to be able to click a link and have the following copied to my clipboard:

Name Email [TAB] Address Phone [TAB] IP Address

How can I "copy" the tab key? And how do I add it to clipboard?

Here's a pure JavaScript solution. It works in Chrome 43+ and Internet Explorer. You'll need to use Flash or a library for cross-browser support.

You can use document.execCommand('copy') to copy a message from a (hidden) element onto the clipboard.

Clicking the button will copy a message to the clipboard:

 var cutTextareaBtn = document.querySelector('.js-textareacutbtn'); var cutTextarea = document.querySelector('.js-cuttextarea'); cutTextarea.textContent = "Name Email\\tAddress Phone\\tIP Address"; cutTextareaBtn.addEventListener('click', function(event) { cutTextarea.select(); try { var successful = document.execCommand('copy'); var msg = successful ? 'successful' : 'unsuccessful'; console.log('Copy text command was ' + msg); } catch(err) { console.log('Oops, unable to copy'); } }); 
 <textarea class="js-cuttextarea">fdsfsd</textarea> <button class="js-textareacutbtn">Copy to clipboard</button> 

Code adapted from this HTML5 rocks article .

This works in Chrome 43+ and Internet Explorer, though support for other browsers is limited - see caniuse.com .

I think it's not possible with Javascript to do a copy/paste to the clipboard feature. You need Flash script to do that. Or, you may use this library but you'll still use Adobe flash: https://github.com/zeroclipboard/zeroclipboard

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM