Skip to content

Commit

Permalink
Add example of browser binding
Browse files Browse the repository at this point in the history
  • Loading branch information
zcbenz committed Apr 3, 2024
1 parent fdfd336 commit a6e86f4
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 4 deletions.
24 changes: 24 additions & 0 deletions app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<html>
<head>
<style>
* { font-family: -apple-system, "Segoe UI", Helvetica, Arial, sans-serif; }
html { color: #333; font-size: 1.2em; }
body { max-width: 40rem; padding: 2rem; margin: auto; }
</style>
</head>
<body>
<p>
User agent: <strong id="browserVersion"></strong>.
</p>
<p>
And the Node.js version is <strong id="nodeVersion"></strong>.
</p>
<script>
function reportNodeVersion(ver) {
nodeVersion.innerText = ver;
}
browserVersion.innerText = navigator.userAgent;
requestNodeVersion();
</script>
</body>
</html>
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"appId": "org.yue.boilerplate",
"productName": "Boilerplate",
"copyright": "Copyright © 2024 Yue. All rights reserved.",
"unpackDir": "assets/icons",
"unpackDir": "app",
"ignore": [
"assets/build"
],
Expand Down
38 changes: 35 additions & 3 deletions src/gui-main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import gui from 'gui';

// Check if it is Yode.
Expand All @@ -13,11 +15,41 @@ if (process.platform == 'darwin') {
guiMain();
}

// Create main window.
let mainWindow: gui.Window;
// Create GUI.
function guiMain() {
mainWindow = gui.Window.create({});
registerCustomProtocol();

// Create main window.
const mainWindow = gui.Window.create({});
mainWindow.setContentSize({width: 400, height: 400});
mainWindow.setContentView(createBrowser());
mainWindow.center();
mainWindow.activate();

// Make it global to prevent garbage collection.
global.mainWindow = mainWindow;
}

// Register a custom protocol that maps to files.
function registerCustomProtocol() {
gui.Browser.registerProtocol('app', (url) => {
const u = new URL(url);
const p = path.resolve(__dirname, '..', 'app', u.pathname.substr(1));
// realpathSync can convert the path to the real place after packaged.
return gui.ProtocolFileJob.create(fs.realpathSync(p));
});
}

// Create a browser view with custom protocol.
function createBrowser() {
const browser = gui.Browser.create({
devtools: true,
contextMenu: true,
webview2Support: true,
});
browser.addBinding('requestNodeVersion', () => {
browser.executeJavaScript(`reportNodeVersion('${process.version}')`, () => {});
});
browser.loadURL('app://host/index.html');
return browser;
}

0 comments on commit a6e86f4

Please sign in to comment.