0

I want to write a function that can add text into your clipboard and show the added text with your copied text when to paste it.

document.addEventListener('copy', function(e){
    e.clipboardData.appendChild(document.createTextNode("hello,world"));
});
<p>I've included the basic site layout so we aren't wasting time creating the form </p>
<p>and making the site looks pretty.</p>

My try failed.
When you copy part of the second line ,for example looks pretty,and pasted it into a leafpad,it will show:

looks pretty hello,world

instead of

looks pretty
chackerian
  • 1,301
  • 2
  • 15
  • 29
  • 1
    Possible duplicate of [How to add extra info to copied web text](https://stackoverflow.com/questions/2026335/how-to-add-extra-info-to-copied-web-text) – AuxTaco Oct 06 '18 at 07:17

1 Answers1

-1

Read on this : https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

This should work given that you have the permissions! Note that permissions to navigator.clipboard are granted only for pages served over HTTPS.

document.addEventListener('copy', function(e){
    appendToClip("+hello,world");
});

function updateClipboard(newClip) {
  console.log('updateClipboard', newClip);
  navigator.clipboard.writeText(newClip).then(function() {
    /* clipboard successfully set */
  }, function() {
    /* clipboard write failed */
  });
}

function appendToClip(text) {
  console.log('appendToClip', text);
navigator.permissions.query({name: "clipboard-write"}).then(result => {
  console.log(result.state);

  // Listen for changes to the permission state
  result.onchange = () => {
    console.log(result.state);
    if (result.state == "granted" || result.state == "prompt") {
      navigator.clipboard.readText().then(
        clipText =>
       updateClipboard(clipText + text));
    } else {
      console.log('appendToClip: not allowed | ', result.state);
  }
  };


});
}



<div> test text </div>
Deian
  • 1,237
  • 15
  • 31