Joseph Nannepaga
Joseph Nannepaga

Reputation: 195

copy and paste through buttons using javascript?

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()} />

Upvotes: 2

Views: 2633

Answers (2)

Joseph Nannepaga
Joseph Nannepaga

Reputation: 195

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'/>

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

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()} />

Upvotes: 2

Related Questions