最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - (Javascript) execCommand('copy') copies text but adds extra white space to value - Stack Overflow

programmeradmin3浏览0评论

I have been scouring the internet all night to figure out how to use the execCommand('copy') feature. Finally, found a solution on that works incredibly well. However, my new dilemma is that when I press the button that copies the value from the input field it adds extra white space to it. So with a normal copy/paste action (Ctl+E and Ctl+V) the input value appears like this:

TESTTESTTESTTEST

But when I press the button to copy the input value to the clipboard it looks like this:

TEST

TEST

TEST

TEST

How do I remove the extra white space that the execCommand('copy') adds to the value of the input field. I have tried .replace(" ", ""); but that does not work. I am unsure how to continue. Here is the code:

function copyValueToClipBoard(containerid) {
var valueToBeCopied = document.getElementById(containerid);
var range = document.createRange();
range.selectNode(valueToBeCopied);
window.getSelection().addRange(range);
  try {  
    // Now that we've selected the anchor text, execute the copy mand  
    var successful = document.execCommand('copy');  
    var msg = successful ? 'successful' : 'unsuccessful';  
    console.log('Copy email mand was ' + msg);  
  } catch(err) {  
    console.log('Oops, unable to copy');  
  }  

  // Remove the selections - NOTE: Should use
  // removeRange(range) when it is supported  
  window.getSelection().removeAllRanges(); 
  };
<!DOCTYPE html>
<html>
<head>
<title>Customer Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>

<b>First Name:</b><input type = "text" id = "firstName"/><button onclick = "copyValueToClipBoard('firstName')">Copy to Clipboard</button>
<textarea rows="50" cols="50"></textarea>
<br>
 </body>
</html>

I have been scouring the internet all night to figure out how to use the execCommand('copy') feature. Finally, found a solution on https://developers.google./web/updates/2015/04/cut-and-copy-mands?hl=en that works incredibly well. However, my new dilemma is that when I press the button that copies the value from the input field it adds extra white space to it. So with a normal copy/paste action (Ctl+E and Ctl+V) the input value appears like this:

TESTTESTTESTTEST

But when I press the button to copy the input value to the clipboard it looks like this:

TEST

TEST

TEST

TEST

How do I remove the extra white space that the execCommand('copy') adds to the value of the input field. I have tried .replace(" ", ""); but that does not work. I am unsure how to continue. Here is the code:

function copyValueToClipBoard(containerid) {
var valueToBeCopied = document.getElementById(containerid);
var range = document.createRange();
range.selectNode(valueToBeCopied);
window.getSelection().addRange(range);
  try {  
    // Now that we've selected the anchor text, execute the copy mand  
    var successful = document.execCommand('copy');  
    var msg = successful ? 'successful' : 'unsuccessful';  
    console.log('Copy email mand was ' + msg);  
  } catch(err) {  
    console.log('Oops, unable to copy');  
  }  

  // Remove the selections - NOTE: Should use
  // removeRange(range) when it is supported  
  window.getSelection().removeAllRanges(); 
  };
<!DOCTYPE html>
<html>
<head>
<title>Customer Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>

<b>First Name:</b><input type = "text" id = "firstName"/><button onclick = "copyValueToClipBoard('firstName')">Copy to Clipboard</button>
<textarea rows="50" cols="50"></textarea>
<br>
 </body>
</html>

Share Improve this question asked Dec 27, 2015 at 3:52 zombie dude 789zombie dude 789 1633 silver badges15 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

The problem is with the selection. Window.getSelection normally works with element nodes and text nodes. In your case, you are selecting the whole input node, which gives you the result you have. With normal nodes, you could select the text node only, but inputs don't have text nodes.

But inputs have setSelectionRange method, which allows to select the value only. Using selectionEnd property, you can select the whole value, but note the whole node. Like this:

function copyValueToClipBoard(containerid) {
var valueToBeCopied = document.getElementById(containerid);
valueToBeCopied.setSelectionRange(0, valueToBeCopied.selectionEnd)

  try {  
    // Now that we've selected the anchor text, execute the copy mand  
    var successful = document.execCommand('copy');  
    var msg = successful ? 'successful' : 'unsuccessful';  
    console.log('Copy email mand was ' + msg);  
  } catch(err) {  
    console.log('Oops, unable to copy');  
  }  

  // Remove the selections - NOTE: Should use
  // removeRange(range) when it is supported  
  window.getSelection().removeAllRanges(); 
  };
<!DOCTYPE html>
<html>
<head>
<title>Customer Information</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>

<body>

<b>First Name:</b><input type = "text" id = "firstName"/><button onclick = "copyValueToClipBoard('firstName')">Copy to Clipboard</button>
<textarea rows="50" cols="50"></textarea>
<br>
 </body>
</html>

The problem is that your range is like selecting across the whole input from before it to after it, so you get the whitespace padding as if you did that. Instead work with the selection straight off

Here is how you might do it without destroying a previous selection the user may have made

function contentsToClipboard(node) {
    var selection = window.getSelection(),
        range;
    // backup
    if (selection.rangeCount)
        range = selection.getRangeAt(0);
    // empty selection in your favourite way
    selection.removeAllRanges();
    // select input contents
    node.selectionStart = 0;
    node.selectionEnd = node.value.length;
    // copy
    try {
        console.log(
            'Copy mand was ' + 
            ['un', ''][+document.execCommand('copy')] + 
            'successful'
        );
    } catch (err) {
        console.log('Oops, unable to copy');
    }
    // restore
    selection.removeAllRanges();
    if (range)
        selection.addRange(range);
}

window.addEventListener('load', function () {
    var foo = document.getElementById('foo');
    document.getElementById('bar').addEventListener('click', function (e) {
        contentsToClipboard(foo);
    });
});
foo <input id="foo" type="text" value="fizzbuzz" /> bar <input id="bar" type="button" value="copy" />

Simpliest way is to use .trim()

The suggested solution didn't work for me, so basing on it I made my one. It removes the space, which appears at the beginning of copied line. Here is the code:

copy() {
    var element = document.getElementById("elementId") as HTMLInputElement;
    element.select();
    element.setSelectionRange(1, element.selectionEnd);
    document.execCommand('copy');
  }
发布评论

评论列表(0)

  1. 暂无评论