förschter
förschter

Reputation: 860

Electron load remote URL and execute javascript

I'm trying to load a website in electron by loading an URL like this

mainWindow.loadURL('http://localhost/index.html')

but like this the javascript on the website doesn't load. The following solution works: Add the following code around the app.js that is loaded in the index.html

<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>

but is not optimal as I'm most likely not allowed to change the code of the website itself. Are there any other options for simply wrapping a website in electron?

Upvotes: 3

Views: 15811

Answers (2)

Tracy Zhou
Tracy Zhou

Reputation: 734

This is just example add to Chris Riebschlager's answer. Load google.com in main.js

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;
    });
}

Script googleWindow.js referenced above:

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

setTimeout(function(){ alert("Hello");search(); }, 3000);

The above script alert "Hello" after 3 seconds, and enter "test" in the search box on google.com.

You can also send an event from the main process as a trigger, use the webContents of the window.

Upvotes: 2

Chris Riebschlager
Chris Riebschlager

Reputation: 1333

You'll want to set nodeIntegration to false in your BrowserWindow settings. That should resolve the issue. Have a look at webPreferences on this page: https://github.com/electron/electron/blob/master/docs/api/browser-window.md

Upvotes: 7

Related Questions