2

I have designed my own context menu, wherein I have declared cut,copy,paste options. cut and copy are working fine. Paste is not at all working. If I'm using cut/copy through button and pressing ctrl+v then its getting pasted. I need to use a button to paste the copied text. Please help me out.

Please help me to finish this. -

handleCut=(e)=>{
document.execCommand('cut');
}

handlePaste=(e)=>{
document.execCommand('Paste');
}
<input type='button' value='Cut' onClick={handleCut()} />
<input type='button' value='Paste' onClick={handlePaste()} />

1
  • navigator.clipboard doesn't work in the reactJs. Tried that Commented Feb 24, 2019 at 5:49

2 Answers 2

2

Try this

handleCut = (e) => {
  document.querySelector('#a').select();
  document.execCommand('cut');
}

handlePaste = () => {
  navigator.clipboard.readText().then(text => document.querySelector('#a').value = text);
}
<input id="a">
<input type='button' value='Cut' onClick={handleCut()} />
<input type='button' value='Paste' onClick={handlePaste()} />

Sign up to request clarification or add additional context in comments.

Comments

0

We can paste as plain Text but not the HTML as that is restricted from the browsers end.

onPaste=(event)=>{
try{
     
      if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
      {
         let clipboard_data=window.clipboardData.getData('text');
        // IE <= 10
        if (document.selection){
            var range = document.selection.createRange();
                range.pasteHTML(clipboard_data);
        // IE 11 && Firefox, Opera .....
        }else if(document.getSelection){
            var range = document.getSelection().getRangeAt(0);
            var nnode = document.createElement("SPAN");
                range.surroundContents(nnode);
                nnode.innerHTML =  clipboard_data;
         };
      }
      else if(navigator.userAgent.indexOf("Chrome") != -1 )
      {
          console.log(navigator.userAgent)
          navigator.clipboard.readText()
          .then(text => {
            document.execCommand('insertHTML',false,text);
          })
          .catch(err => {
            console.error('Failed to read clipboard contents: ', err);
          }); 
      }
  
      else 
      {
        alert("Your browser doesn't support Paste")
      }
     
    }
    catch(errMsg)
    {
      alert("Your browser doesn't support Paste");
    }
    finally{
    this.setState({showContextMenu:false})
  }
  
}
<input type='button' onClick={this.onPaste} value='Paste'/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.