webview_deno icon indicating copy to clipboard operation
webview_deno copied to clipboard

Fixing examples/server.ts (use of worker of Deno)

Open javacommons opened this issue 2 years ago • 0 comments

Regarding https://github.com/webview/webview_deno/blob/main/examples/server.ts

// FIXME: Blocks the main thread and // no further requests can be served.

The code below would help fix the above problem, using worker of Deno.

<server.ts>

import { getAvailablePortSync } from "https://deno.land/x/port/mod.ts";
import { Webview } from "https://deno.land/x/webview/mod.ts";

const port = getAvailablePortSync();

const worker = new Worker(new URL("./worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({ command: "serve", port: port });

const webview = new Webview();
webview.navigate(`http://localhost:${port}`);
webview.run();
worker.postMessage({ command: "quit" });

<worker.ts>

import { serve } from "https://deno.land/std/http/server.ts";

self.onmessage = async (e) => {
    switch (e.data.command) {
        case "serve": {
            const { port } = e.data;
            serve((_req) => new Response("Hello, world"), { port: port });
        } break;
        case "quit": {
            self.close();
        } break;
    }
};

javacommons avatar Jun 23 '22 12:06 javacommons