在我的主要过程中,我创建了一个渲染器窗口:
var mainWindow = new BrowserWindow({
height: 600,
width: 800,
x: 0,
y: 0,
frame: false,
resizable: true
});
mainWindow.openDevTools();
mainWindow.loadURL('file://' + __dirname + '/renderer/index.html');
Run Code Online (Sandbox Code Playgroud)
然后我想以某种方式与它沟通:
mainWindow.webContents.send('message', 'hello world');
Run Code Online (Sandbox Code Playgroud)
但是,主窗口不会收到此消息,因为在我尝试发送它时未完全创建它.
我通过将后一个代码包装在setTimeout()中暂时解决了这个问题,但这绝对不是解决竞争条件的正确方法.
主窗口准备就绪时是否有回调?我尝试了文档中提到的"准备展示"活动,但它没有用.
小智 16
"mainWindow"上的监听器对我不起作用.我改为使用"mainWindow.webContents".
mainWindow.webContents.once('dom-ready', () => {});
Run Code Online (Sandbox Code Playgroud)
小智 7
检查这个:https : //github.com/electron/electron/blob/master/docs/api/web-contents.md
您可以使用此事件来了解您的 main.js [CASE 1] 中的窗口是否已准备就绪,但是如果想知道您的页面何时完全加载,您应该在 index.html [CASE 2] 中添加一个事件,然后您可以附加一个函数,向他的父 Main.js 发送消息告诉他,他准备好了,使用 IPCRenderer 和 IPCmain
情况1
主要.js:
mainWindows.webContents.on('did-finish-load',WindowsReady);
function WindowsReady() {
console.log('Ready');
}
Run Code Online (Sandbox Code Playgroud)
案例二
html:
<script>
const {ipcRenderer} = require('electron');
document.addEventListener('DOMContentLoaded',pageLoaded);
function pageLoaded(){
alert('The page is loade');
ipcRenderer.send('Am_I_Ready',"Im ready");
}
</script>
Run Code Online (Sandbox Code Playgroud)
主要.js:
const {ipcMain} = electron;
ipcMain.on('Am_I_Ready', doSomething)
function doSomething(){
console.log('Everything is ready.');
}
Run Code Online (Sandbox Code Playgroud)
小智 7
像这样使用 mainWindow.webContents :
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.send('message', 'hello world');
}
Run Code Online (Sandbox Code Playgroud)
看看Electron浏览器窗口文档中did-finish-load提到的事件。
mainWindow.once('did-finish-load', () => {
// Send Message
})
Run Code Online (Sandbox Code Playgroud)
似乎也有一个dom-ready 事件。
在先前的答案中未提到的,loadURL返回一个承诺,该承诺在触发“ did-finish-load”事件的同时进行解析;也就是说,它们本质上是等效的,除了一个是一个承诺,另一个是一个回调。
| 归档时间: |
|
| 查看次数: |
17570 次 |
| 最近记录: |