我正在构建一个不能使用webview
的应用程序,因为它无法完成我想做的所有事情,而使用mainWindow
可以做到。
但是,我需要使用整个javascript文件,而不仅仅是文本。
示例:
const {app, BrowserWindow} = require('electron');
let mainWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
width: 1024,
height: 1024
});
mainWindow.loadURL("https://www.google.com/");
mainWindow.webContents.executeJavaScript('alert("this is a test!");');
// I want to load an entire file for the .executeJavaScript()
// I have a file within the same directory called 'index.js'
// How would I implement this?
mainWindow.webContents.executeJavaScript('???');
});
答案 0 :(得分:0)
如何将文件读取为字符串并执行它?
const fs = require("fs");
const js = fs.readFileSync('./somefile.js').toString();
mainWindow.webContents.executeJavaScript(js);
答案 1 :(得分:0)
我遇到了相同的要求,这是我的工作方式,在npm安装xmlhttprequest之后,使用以下代码段使用executeJavaScript方法从文件执行脚本
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var scriptDirectory='file://' + __dirname + "/scripts/script-ext.js" //given that the scripts folder exists in your project's parent directory
var rawFile = new XMLHttpRequest();
rawFile.open("GET",scriptDirectory,false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
console.log(allText) //this will log your script file code content to be executed
mainWindow.webContents.executeJavaScript(allText)
}
}
}
rawFile.send(null);