clipboard 

Send to Kindle
home » snippets » javascript » clipboard



Snippets

selection.selectAllChildren(text);

// This is my current solution.

function set_clipboard_text(text) {
  console.log("CKCK: Setting clipboard text: %s", text);

  // This method uses a temporary DOM node.  We'll use a div here.
  var node = document.createElement("div"); 
  node.textContent = text;
  document.body.appendChild(node);

  // Select the new node
  var selection = window.getSelection();
  selection.selectAllChildren(node);  // This automatically loses the previous selection.

  // Could alternatively also use:
  //
  //   var selection = window.getSelection();
  //   var range = document.createRange();
  //   range.selectNodeContents(text);
  //   selection.removeAllRanges();
  //   selection.addRange(range);

  // Perform the copy.
  document.execCommand("copy", false, null);

  // Now get rid of this temp node.
  document.body.removeChild(node); 
}