Search code examples
javascriptcontenteditablepasteexeccommand

Trying to programmically paste


I am having trouble with execCommand('paste');

My code:

  var copy = document.createElement("BUTTON");
  copy.innerText = "Copy";
  Sections.contextmenu.appendChild(copy);
  copy.addEventListener("click", function(e) {
    document.execCommand("copy");
  });

  var paste = document.createElement("BUTTON");
  Sections.contextmenu.appendChild(paste);
  paste.innerText = "Paste";
  paste.addEventListener("click", function(e) {
    console.log("Paste");
    if (document.execCommand("paste")) {
      console.log("pasted");
    }
  });

Copy worked right out of the box. I cannot get paste to work. I see "Paste" in the console, but nothing is pasted. I've read some things that say that this functionality needs to be explicitly turned on in Firefox. Is there no way (other than using flash... This is talked about in the research I've done) to execute "paste" in a content-editable element programmatically?


Solution

  • The paste command is disabled in web content (it’s only available in a browser extension). It’s disabled presumably because it would allow any website to steal the clipboard’s content. From the MDN documentation on execCommand:

    paste

    Pastes the clipboard contents at the insertion point (replaces current selection). Disabled for web content.