Copy to clipboard with break line

后端 未结 4 1380
你的背包
你的背包 2020-12-01 12:53

I want to copy a text to clipboard but in a new line.

Problem:

If you click the button in the snippet and paste in the notepad this is what

4条回答
  •  感动是毒
    2020-12-01 13:17

    Non-jQuery Solution to simply copy a string with line breaks to clipboard

    Please refer to code comments for clarity.

    function copyStringWithNewLineToClipBoard(stringWithNewLines){
    
        // Step 1: create a textarea element.
        // It is capable of holding linebreaks (newlines) unlike "input" element
        const myFluffyTextarea = document.createElement('textarea');
        
        // Step 2: Store your string in innerHTML of myFluffyTextarea element        
        myFluffyTextarea.innerHTML = stringWithNewLines;
        
        // Step3: find an id element within the body to append your myFluffyTextarea there temporarily
        const parentElement = document.getElementById('any-id-within-any-body-element');
        parentElement.appendChild(myFluffyTextarea);
        
        // Step 4: Simulate selection of your text from myFluffyTextarea programmatically 
        myFluffyTextarea.select();
        
        // Step 5: simulate copy command (ctrl+c)
        // now your string with newlines should be copied to your clipboard 
        document.execCommand('copy');
    
        // Step 6: Now you can get rid of your fluffy textarea element
        parentElement.removeChild(myFluffyTextarea);
        }
    

提交回复
热议问题