如何在电子应用程序的html上从nodejs看到os.hostname()模块?



这是我的第一个帖子,所以我很抱歉。我正在努力尝试在电子应用程序的html页面中显示来自nodejs的os.hostname()模块,我在终端中获得主机名,但当我运行它时,我无法让它显示在应用程序页面上。

这是我的代码:

Javascript(index.js)

const { app, BrowserWindow, Tray, Menu} = require('electron');
const os = require('os');
if(os.hostname()) {
var hostname = os.hostname();
console.log("Hostname for the operating system is " + String(hostname));
}
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL(`file://${__dirname}/index.html`)
tray = new Tray('pic.PNG')
tray.setToolTip('Tray App')
tray.on("click",() =>{
mainWindow.isVisible()?mainWindow.hide():mainWindow.show()
let template =[{label:'Hostname'},{label:'DNS'}]
let contextMenu= Menu.buildFromTemplate(template)
tray.setContextMenu(contextMenu)
})
})

Html(index . html)

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link href="style.css" rel="stylesheet" type="text/css">
<Title>App</Title>
</head>
<body>
<div class="header">
<img src="picbig.png" alt="logo" />
<h1>Wellcome</h1>
</div>
<p>Hostname:<span id="Hostname"></span></p>
<script src="renderer.js"></script>
</body>
</html>

我希望我弄清楚了,如果有人需要任何额外的信息,所以你可以帮助我,让我知道!提前谢谢你。

我尝试了各种方法,我可以找到在html中显示一个javascript var,但它没有工作:(

我设法做到了,我缺少一个连接所有内容的预加载文件。

下面是代码(和包的源代码)。Json,但我不会显示它,因为当你创建一个新的电子项目时它是默认的):

main.js

const { app, BrowserWindow, ipcMain } = require('electron');
const os = require('os');
let mainWindow;
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: __dirname + '/preload.js'
}
});
mainWindow.loadFile('index.html');
mainWindow.on('closed', function () {
mainWindow = null;
});
}
app.on('ready', createWindow);
ipcMain.handle('getHostname', async (event, arg) => {
return os.hostname();
});

preload.js

const { ipcRenderer } = require('electron');
window.addEventListener('DOMContentLoaded', () => {
ipcRenderer.invoke('getHostname').then(hostname => {
document.getElementById('hostname').textContent = `Hostname: ${hostname}`;
});
});

index . html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Electron App</title>
</head>
<body>
<h1 id="hostname"></h1>
<script src="renderer.js"></script>
</body>
</html>

最新更新