Skip to content

Commit

Permalink
feat: add autoReconnect options for channel to reconnect when port di…
Browse files Browse the repository at this point in the history
…sconnected or pageshow from bfcache
  • Loading branch information
tanlethanh committed Jul 27, 2024
1 parent 246fac3 commit bad8c4e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
37 changes: 34 additions & 3 deletions src/chrome/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,43 @@ import type { RawRequest } from '../core/types';
export class ChromeChannel extends AsyncChannel {
connection: chrome.runtime.Port;

constructor(channelId: string) {
constructor(
channelId: string,
/**
* use autoReconnect will listen to disconnect event and pageshow from bfcache to reconnect to the kernel
*/
autoReconnect?: boolean,
) {
super();
this.connection = chrome.runtime.connect({ name: channelId });
this.connection.onMessage.addListener((message) => {
this.connection = this.connect(channelId, autoReconnect);

if (autoReconnect) {
window?.addEventListener('pageshow', (event) => {
if (event.persisted) {
console.warn('Page restored from bfcache, reconnect');
this.connection = this.connect(channelId, autoReconnect);
}
});
}
}

private connect(
channelId: string,
autoReconnect?: boolean,
): chrome.runtime.Port {
const connection = chrome.runtime.connect({ name: channelId });
connection.onMessage.addListener((message) => {
this.handleIncoming(message);
});

if (autoReconnect) {
connection.onDisconnect.addListener(() => {
console.warn('Port disconnected, attempting to reconnect...');
this.connection = this.connect(channelId, autoReconnect);
});
}

return connection;
}

push(payload: RawRequest): void {
Expand Down
2 changes: 1 addition & 1 deletion src/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@metacraft/crab",
"version": "0.0.5",
"version": "0.0.6",
"description": "A universal messaging library for cross-platform applications",
"author": "https://metacraft.studio",
"license": "MIT",
Expand Down

0 comments on commit bad8c4e

Please sign in to comment.