如何在 Electron 渲染的网页上调用 JavaScript 函数?

2022-01-10 00:00:00 node.js electron javascript

我正在尝试使用 Twitter 编写一个包装器.io/" rel="noreferrer">Electron(以前的 Atom Shell).

I'm trying to write a wrapper for Twitter using Electron (formerly Atom Shell).

我的 main.js 文件(它看起来几乎与Hello World"的例子,我只是在一个地方改了):

My main.js file (it looks almost identical to the "Hello World" example, I just changed it in one place):

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the javascript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  if (process.platform != 'darwin')
    app.quit();
});

// This method will be called when atom-shell has done everything
// initialization and ready for creating browser windows.
app.on('ready', function() {

  // Create the browser window.
  mainWindow = new BrowserWindow ({'width':1000,'height':600});
  // and load the index.html of the app.
  mainWindow.loadUrl('https://twitter.com');

  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});

我尝试在 mainWindow.loadUrl() 之后立即调用 alert() 函数,但它没有执行.

I try to call alert() function right after mainWindow.loadUrl() but it does not execute.

我知道 main.js 文件就像我的应用程序的服务器端,但问题是……如何在页面上调用 JavaScript 函数?我应该在哪里写代码?

I understand that main.js file is like the server side of my app, but the question is... How can I call a JavaScript function on page? Where should I write the code?

例如,我想执行此操作:

For example, I want to perform this:

$(document).ready(function() {
    alert("Hurray!");
});

推荐答案

我已经解决了这个问题.下面是示例代码:

I have solved the problem. Here's the example code:

...

app.on('ready', function() {

  ...

  mainWindow.webContents.on('did-finish-load', function() {
    mainWindow.webContents.executeJavaScript("alert('Hello There!');");
  });

  ...

});

相关文章