page8.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var sshTerm = null;
  2. var sshFit = null;
  3. var sshWS = null;
  4. var sshResizeTimer = null;
  5. function initPage8() {
  6. var el = document.getElementById("ssh-terminal");
  7. if (!el || sshTerm) {
  8. return;
  9. }
  10. // xterm.js 不支持 IE 等老浏览器, 优雅降级提示
  11. if (typeof Terminal === "undefined") {
  12. el.innerHTML =
  13. '<div style="padding:24px;text-align:center;color:#94a3b8;line-height:1.8;">' +
  14. "当前浏览器不支持 SSH 终端组件。<br>" +
  15. "请使用 Chrome、Edge、Firefox 等现代浏览器访问该功能。</div>";
  16. return;
  17. }
  18. sshTerm = new Terminal({
  19. cursorBlink: true,
  20. scrollback: 2000,
  21. fontSize: 14,
  22. convertEol: true,
  23. theme: {
  24. background: "#111111",
  25. },
  26. });
  27. sshFit = new FitAddon.FitAddon();
  28. sshTerm.loadAddon(sshFit);
  29. sshTerm.open(el);
  30. sshTerm.onData(function (data) {
  31. if ((sshWS && sshWS.readyState) === WebSocket.OPEN) {
  32. sshWS.send(
  33. JSON.stringify({
  34. type: "input",
  35. data: data,
  36. })
  37. );
  38. }
  39. });
  40. connectSSH();
  41. window.addEventListener("resize", resizeSSH);
  42. resizeSSH();
  43. }
  44. function connectSSH() {
  45. sshWS = new WebSocket(
  46. (location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/api/ssh/ws"
  47. );
  48. sshWS.binaryType = "arraybuffer";
  49. sshWS.onopen = function () {
  50. resizeSSH();
  51. sshTerm && sshTerm.focus();
  52. };
  53. sshWS.onmessage = function (e) {
  54. sshTerm && sshTerm.write(new Uint8Array(e.data));
  55. };
  56. sshWS.onclose = function () {
  57. sshWS = null;
  58. sshTerm && sshTerm.write("\r\n\x1b[33m[Connection closed]\x1b[0m\r\n");
  59. };
  60. }
  61. function resizeSSH() {
  62. if (!sshFit || !sshTerm) {
  63. return;
  64. }
  65. clearTimeout(sshResizeTimer);
  66. sshResizeTimer = null;
  67. sshResizeTimer = setTimeout(function () {
  68. if (!sshTerm || !sshFit) {
  69. return;
  70. }
  71. sshFit.fit();
  72. if ((sshWS && sshWS.readyState) === WebSocket.OPEN) {
  73. sshWS.send(
  74. JSON.stringify({
  75. type: "resize",
  76. cols: sshTerm.cols,
  77. rows: sshTerm.rows,
  78. })
  79. );
  80. }
  81. }, 100);
  82. }
  83. function exitPage8() {
  84. window.removeEventListener("resize", resizeSSH);
  85. clearTimeout(sshResizeTimer);
  86. if (sshWS) {
  87. sshWS.onclose = null;
  88. sshWS.close();
  89. sshWS = null;
  90. }
  91. sshTerm && sshTerm.dispose();
  92. sshTerm = null;
  93. sshFit = null;
  94. }