加载远程URL并执行javascript

加载远程URL并执行javascript,javascript,electron,Javascript,Electron,我正试图通过加载这样的URL在electron中加载一个网站 mainWindow.loadURL('http://localhost/index.html') 但像这样,网站上的javascript不会加载。 以下解决方案有效: 在index.html中加载的app.js周围添加以下代码 <script>if (typeof module === 'object') {window.module = module; module = undefined;}</script&

我正试图通过加载这样的URL在electron中加载一个网站

mainWindow.loadURL('http://localhost/index.html')
但像这样,网站上的javascript不会加载。 以下解决方案有效: 在index.html中加载的app.js周围添加以下代码

<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>
<script src="/app/app.js"></script> 
<script>if (window.module) module = window.module;</script>
if(typeof module=='object'){window.module=module;module=undefined;}
如果(window.module)module=window.module;
但这不是最优的,因为我很可能不被允许更改网站本身的代码。
用electron包装网站还有其他选择吗?

您需要在
浏览器窗口设置中将
节点集成设置为false。这应该解决问题。请在此页面上查看
webPreferences

这只是添加到Chris Riebschlager答案中的示例。 在main.js中加载google.com

let googleWindow;

// handle create googleWindow
function createGoogleWindow(){
    googleWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true,
            preload:`${__dirname}/scripts/googleWindow.js`
          }});
    //load html into window
    googleWindow.loadURL('https://www.google.com/');
    //garbage collection handle
    googleWindow.on('close', function(){
        googleWindow=null;
    });
}
上面引用的脚本googleWindow.js:

const electron = require('electron');
function search(){
    const input = document.querySelector('input[name="q"]');
    input.value = "test";
}

setTimeout(function(){ alert("Hello");search(); }, 3000);
上述脚本在3秒钟后发出“Hello”警报,并在google.com上的搜索框中输入“test”

您还可以使用窗口的WebContent从主进程发送事件作为触发器