Skip to content

Commit

Permalink
Use runtime.connectNative() for Deno host
Browse files Browse the repository at this point in the history
 Deno exits child process when parent process exits denoland/deno#5501
  • Loading branch information
guest271314 authored Dec 25, 2022
1 parent 8e1c5e7 commit 47303e7
Showing 1 changed file with 49 additions and 40 deletions.
89 changes: 49 additions & 40 deletions nativeTransferableStream.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,52 @@
onload = () => {
chrome.runtime.sendNativeMessage(
'native_messaging_espeakng',
{},
async (nativeMessage) => {
parent.postMessage(nativeMessage, name);
await new Promise((resolve) => setTimeout(resolve, 100));
const controller = new AbortController();
const { signal } = controller;
parent.postMessage('Ready.', name);
onmessage = async (e) => {
console.log(e.data);
if (e.data instanceof Array) {
try {
const { body } = await fetch('https://localhost:8443', {
method: 'post',
cache: 'no-store',
credentials: 'omit',
body: JSON.stringify(e.data),
signal,
});
parent.postMessage(body, name, [body]);
} catch (err) {
parent.postMessage(err, name);
}
} else {
if (e.data === 'Done writing input stream.') {
chrome.runtime.sendNativeMessage(
'native_messaging_espeakng',
{},
(nativeMessage) => {
parent.postMessage(nativeMessage, name);
}
);
}
if (e.data === 'Abort.') {
controller.abort();
}
// Deno exits child process when parent process exits
// https://github.com/denoland/deno/issues/5501
// Use runtime.connectNative()
const handleMessage = async (nativeMessage) => {
port.onMessage.removeListener(handleMessage);
port.onDisconnect.addListener((e) => {
console.log(e);
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
}
});
parent.postMessage(nativeMessage, name);
// Wait 100ms for server process to start
await new Promise((resolve) => setTimeout(resolve, 100));
const controller = new AbortController();
const { signal } = controller;
parent.postMessage('Ready.', name);
onmessage = async (e) => {
console.log(e.data);
if (e.data instanceof Array) {
try {
const { body } = await fetch('https://localhost:8443', {
method: 'post',
cache: 'no-store',
credentials: 'omit',
body: JSON.stringify(e.data),
signal,
});
parent.postMessage(body, name, [body]);
} catch (err) {
parent.postMessage(err, name);
}
};
}
);
} else {
if (e.data === 'Done writing input stream.') {
port.onMessage.addListener((nativeMessage) => {
parent.postMessage(nativeMessage, name);
port.disconnect();
});
port.postMessage(null);
}
if (e.data === 'Abort.') {
controller.abort();
port.disconnect();
}
}
};
};
const port = chrome.runtime.connectNative('native_messaging_espeakng');
port.onMessage.addListener(handleMessage);
port.postMessage(null);
};

0 comments on commit 47303e7

Please sign in to comment.