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

时间:2023-01-29
本文介绍了如何在 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!');");
  });

  ...

});

这篇关于如何在 Electron 渲染的网页上调用 JavaScript 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:电子框架是否允许通过网络工作者进行多线程? 下一篇:如何使用电子获取文件夹路径

相关文章

最新文章