Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xtermjs can not copy & paste

I was not able to implement the copy & paste function from xterm.js APIs. I want the terminal to be able to copy strings from the clipboard.

I'm using

  this.term.onKey((key) => {
    if (key.domEvent.code === 'KeyC'){
     if (key.domEvent.ctrlKey) {
     this.copiedText = this.term.getSelection();
    }
   } else if (key.domEvent.code === 'KeyV'){
     if (key.domEvent.ctrlKey) {
     this.term.write(this.copiedText);
    } 
   }
  }

but it can only get copied text within the terminal and the key event can not detect the command key on MAC (right now I'm using ctl + c & ctl + v)

If I use the onData(), the event is triggered when I press command + V and I can see it outputs strings ouside the terminal

  this.term.onData((data) => {
    console.log(data.toString());  // prints "strings I copied with command + c"
  });

But "data" is just a string and the event is triggered by key press as well, so term.onData will conflict with onKey() event, and I'm not sure how to set a condition on "data" since it is not a object.

like image 325
781850685 Avatar asked May 15 '26 02:05

781850685


1 Answers

You can use Terminal.attachCustomKeyEventHandler for ctrl/cmd+c/v to intercept the key press and prevent it from being evaluated by the terminal.

In that handler you can handle the keypress and use the relevant web APIs to copy and paste the text (document.execCommand or preferably navigator.clipboard).

like image 144
Daniel Imms Avatar answered May 16 '26 16:05

Daniel Imms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!