cmd/tsconnect: use the parent window for beforeunload event listener

The SSH session may be rendered in a different window that the one that
is executing the script.

Signed-off-by: Mihai Parparita <mihai@tailscale.com>
This commit is contained in:
Mihai Parparita 2022-09-12 17:44:35 -07:00 committed by Mihai Parparita
parent 82e82d9b7a
commit 9c6bdae556

View File

@ -14,6 +14,7 @@ export function runSSHSession(
onDone: () => void, onDone: () => void,
terminalOptions?: ITerminalOptions terminalOptions?: ITerminalOptions
) { ) {
const parentWindow = termContainerNode.ownerDocument.defaultView ?? window
const term = new Terminal({ const term = new Terminal({
cursorBlink: true, cursorBlink: true,
allowProposedApi: true, allowProposedApi: true,
@ -57,22 +58,19 @@ export function runSSHSession(
resizeObserver?.disconnect() resizeObserver?.disconnect()
term.dispose() term.dispose()
if (handleBeforeUnload) { if (handleBeforeUnload) {
window.removeEventListener("beforeunload", handleBeforeUnload) parentWindow.removeEventListener("beforeunload", handleBeforeUnload)
} }
onDone() onDone()
}, },
}) })
// Make terminal and SSH session track the size of the containing DOM node. // Make terminal and SSH session track the size of the containing DOM node.
resizeObserver = resizeObserver = new parentWindow.ResizeObserver(() => fitAddon.fit())
new termContainerNode.ownerDocument.defaultView!.ResizeObserver(() =>
fitAddon.fit()
)
resizeObserver.observe(termContainerNode) resizeObserver.observe(termContainerNode)
term.onResize(({ rows, cols }) => sshSession.resize(rows, cols)) term.onResize(({ rows, cols }) => sshSession.resize(rows, cols))
// Close the session if the user closes the window without an explicit // Close the session if the user closes the window without an explicit
// exit. // exit.
handleBeforeUnload = () => sshSession.close() handleBeforeUnload = () => sshSession.close()
window.addEventListener("beforeunload", handleBeforeUnload) parentWindow.addEventListener("beforeunload", handleBeforeUnload)
} }