如何在 Electron 渲染的网页上调用 JavaScript 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28920621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a JavaScript function on a web page rendered by Electron?
提问by evlogii
I'm trying to write a wrapper for Twitterusing Electron(formerly Atom Shell).
我正在尝试使用Electron(以前称为 Atom Shell)为Twitter编写一个包装器。
My main.jsfile (it looks almost identical to the "Hello World" example, I just changed it in one place):
我的main.js文件(它看起来几乎与“ Hello World”示例相同,我只是在一处更改了它):
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;
});
});
I try to call alert()function right after mainWindow.loadUrl()but it does not execute.
我尝试在alert()之后立即调用函数,mainWindow.loadUrl()但它没有执行。
I understand that main.jsfile 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?
我知道main.js文件就像我的应用程序的服务器端,但问题是...如何在页面上调用 JavaScript 函数?我应该在哪里写代码?
For example, I want to perform this:
例如,我想执行此操作:
$(document).ready(function() {
alert("Hurray!");
});
回答by evlogii
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!');");
});
...
});
回答by Konstantin Grushetsky
First of all, you should clearly see the differentiation of processes within Electron (formerly Atom Shell). Electron makes use of the main processas a sort of a back-end (you might call it "server side" as you do) and an entry point of your application. As you probably understand the main process can spawn multiple instances of BrowserWindow, which are actually separate operating system windows each hosting a Chromium rendered web page run in a separate process called renderer process. You can think of renderer process as a simple browser window with potentially extended capabilities, like accessing Node.js modules (I write "potentially", because you can turn off Node.js integration for renderer process).
首先,您应该清楚地看到 Electron(以前称为 Atom Shell)内部的进程差异化。Electron 将主进程用作某种后端(您可能会称其为“服务器端”)和应用程序的入口点。正如您可能理解的那样,主进程可以产生多个实例BrowserWindow,这些实例实际上是独立的操作系统窗口,每个窗口托管一个 Chromium 渲染的网页,运行在一个称为渲染器进程的单独进程中。您可以将渲染器进程视为具有潜在扩展功能的简单浏览器窗口,例如访问 Node.js 模块(我写为“潜在”,因为您可以关闭渲染器进程的 Node.js 集成)。
It should be mentioned that while you have a window with GUI for renderer process, you have none for the main process. In fact, it doesn't make a lot of sense to have one for the back-end logic of your app. So, it is not possible to call alert()directly in the main process and see the alert window. The solution that you proposed shows the alert indeed. But it's important to understand that the pop up is created by the renderer process and not the main process itself! The main process just asks the renderer to show the alert (that's what webContents.executeJavaScriptfunction actually does).
应该提到的是,虽然您有一个带有用于渲染器进程的 GUI 的窗口,但主进程却没有。事实上,为您的应用程序的后端逻辑设置一个并没有多大意义。因此,无法alert()在主进程中直接调用并查看警报窗口。您提出的解决方案确实显示了警报。但重要的是要了解弹出窗口是由渲染器进程创建的,而不是主进程本身!主进程只是要求渲染器显示警报(这就是webContents.executeJavaScript函数实际所做的)。
Secondly, as I understand what you're really trying to achieve here with calling alert()function in the main process is the tracing of program execution. You can call console.log()to output the desired message to console. In this case the application itself must be started from the console:
其次,据我所知,您在这里通过alert()主进程中的调用函数真正想要实现的是程序执行的跟踪。您可以调用console.log()以将所需的消息输出到控制台。在这种情况下,应用程序本身必须从控制台启动:
/path/to/electron-framework/electron /your/app/folder
Now, what's even better is that you can debug the main process. In order to do that the application must be started with the --debug(or --debug-brk) key and the value of the listening port assigned to it. Just like that:
现在,更好的是您可以调试主进程。为此,必须使用--debug(或--debug-brk) 键和分配给它的侦听端口的值来启动应用程序。就像这样:
/path/to/electron-framework/electron --debug=1234 /your/app/folder
You can use any kind of V8 debuggerto attach to the assigned port and start the debugging. That means that theoretically any Node.js debugger must work. Take a look at node-inspectoror WebStorm debugger. There's a popular question here at StackOverflow about debugging Node.js apps: How do I debug Node.js applications?.
您可以使用任何类型的V8 调试器连接到指定的端口并开始调试。这意味着理论上任何 Node.js 调试器都必须工作。看看node-inspector还是WebStorm 调试器。StackOverflow 上有一个关于调试 Node.js 应用程序的流行问题:如何调试 Node.js 应用程序?.
回答by JerryGoyal
The properway is to use contents.send('some_js_Method','parameters')to invoke a javascript method in a web page from main.js
在正确的方法是使用contents.send('some_js_Method','parameters')从网页调用JavaScript方法main.js
// In the main.js
const {app, BrowserWindow} = require('electron')
let win = null
app.on('ready', () => {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(`file://${__dirname}/index.html`)
win.webContents.send(some_js_Method', 'window created!') //calling js method (async call)
})
//in index.html
<html>
<body>
<script>
require('electron').ipcRenderer.on('some_js_Method', (event, message) => {
console.log(message) // Prints 'window created!'
})
</script>
</body>
</html>

