Search code examples
javascriptterminalxtermjs

How to resize xtermjs terminal


I don't know how to resize my xterm.js terminal. Somebody know how to do ? I tried with css but it didn't work.

Thanks in advance.


Solution

  • This is how you can define your xterm base data to set cols and rows:

    let xterm = new Xterm({
        rows: 22,
        cols: x, //any value
    });
    

    To do a resize, you can use fitAddon:

    let fitAddon = new FitAddon();
    xterm.loadAddon(fitAddon);
    fitAddon.fit();
    
    xterm.onResize(function (evt) {
       websocket.send({ rows: evt.rows });
    });
    

    more details about resizing xterm.js terminal here.

    Update

    I think changing the above code for onResize prop to this one bellow and adding xterm_resize_ob will improve the resize functionality:

    xterm.onResize(function (evt) {
      const terminal_size = {
        Width: evt.cols,
        Height: evt.rows,
      };
      websocket.send("\x04" + JSON.stringify(terminal_size));
    });
    
    const xterm_resize_ob = new ResizeObserver(function (entries) {
      // since we are observing only a single element, so we access the first element in entries array
      try {
        fitAddon && fitAddon.fit();
      } catch (err) {
        console.log(err);
      }
    });
    
    // start observing for resize
    xterm_resize_ob.observe(document.querySelector("#xterm"));