# Leave and switch encounters

Closing or reloading the iframe while `canBeClosed` is `false` can lose audio or unsaved note edits. It is your role to prevent users from closing the page or the iframe while unsaved changes are still pending.

## Before leaving[​](#before-leaving "Direct link to Before leaving")

Before a route change, a patient switch, or a tab close:

1. If `canBeClosed` is `false`, call `stopRecording()` or `startNoteGeneration()` when `availableActions` allows it. Both stop the recording. `stopRecording()` only stops it. `startNoteGeneration()` stops it first if needed, then starts the generation. The generation itself runs on Nabla's servers and does not keep `canBeClosed` `false`.
2. Wait with `await client.waitUntilClosable()`.
3. Tear down.

For navigation inside your app, use these steps before you tear down the page.

## Closing or reloading the tab[​](#closing-or-reloading-the-tab "Direct link to Closing or reloading the tab")

`beforeunload` cannot wait for a promise. To warn users who close or reload the tab, check the current state synchronously:

```
window.addEventListener("beforeunload", (event) => {

  if (client.getCurrentState()?.canBeClosed === false) {

    event.preventDefault();

  }

});
```

## Switching encounters[​](#switching-encounters "Direct link to Switching encounters")

One iframe load shows one encounter. To move from encounter A to B:

```
try {

  if (clientA.getCurrentState()?.availableActions.includes("STOP_RECORDING")) {

    await clientA.stopRecording(); // or startNoteGeneration(), to get the note first

  }

  await clientA.waitUntilClosable(); // no timeout: audio may still be uploading

} finally {

  clientA.destroy();

}
```

Then call `create` again with the URL of a new [`POST /encounters`](/connect/reference/create-or-update-encounters.md), or of [`POST /encounters/url`](/connect/reference/generate-encounters-url.md) for an encounter you already created. An encounter URL is single-use and expires in 10 minutes, so a new client always needs a fresh one. See [Launch encounters](/connect/guides/launch-encounters.md).

You can use the same iframe element or a new one. Do not set `src` yourself: the SDK does.

## Destroying the client[​](#destroying-the-client "Direct link to Destroying the client")

A client is bound to one iframe. If another client is created on it, a ready first client emits [`CONTEXT_CHANGED`](/connect/sdk/guides/errors.md#context-changed) and stops. One that is not ready yet gets no error. Call `destroy()` first.

`destroy()` is idempotent and rejects pending commands with [`DESTROYED`](/connect/sdk/guides/errors.md#destroyed). Call it before you remove or replace the iframe.
