简体   繁体   中英

Electron window shows a screenshot of the screen

So I have an electron app named main.js which I start with npm start . I've set the start script in package.json to electron main.js and have also tried electron . . When running npm start , everything starts without any errors but the electron window only shows a snapshot of what was on the screen when I started it. I've tried refreshing it but nothing seems to work. Here is how it looks: Image It should view localhost:3001 but it doesn't. I've also tried to run electron . directly in the terminal but that gives me electron: command not found . When running ./node_modules/electron/dist/electron . it starts as it should but the same problem occurs. Here is main.js :

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const core = require('./app');

let mainWindow

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: { webSecurity: false },
        nodeIntegration: false,
    })

    mainWindow.loadURL('http://localhost:3001');

    // mainWindow.setFullScreen(true)

    // mainWindow.setMenu(null);

    mainWindow.webContents.openDevTools()

    mainWindow.on('closed', function () {
        mainWindow = null
    })

    console.log('Electron window ready')
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
    app.quit()
})

core.start()

It seems you didn't install Electron globally, for that you need to run npm install -g Electron

Replace mainWindow.loadURL('http://localhost:3001'); With:

mainWindow.loadURL(
  url.format({
    pathname: path.join(__dirname, "index.html"),
    protocol: "file:",
    slashes: true
  })
);

You have not shared your package.json file, but I will guess you did not run npm install --save electron in your terminal.

Also, instead of:

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

you want to write it like so:

const electron = require('electron');
const { app, BrowserWindow } = electron;

I would review ES6 destructuring and unless you did not share the code with us, you should start your electron project by assuring that the app object is ready and loading your file like so:

let mainWindow;

app.on('ready', () => {
  mainWindow = new BrowserWindow({});
  mainWindow.loadURL(`file://${__dirname}/main.html`);
});

You will notice I declared an empty mainWindow variable to take care of any scoping issues you may have as you may have to use mainWindow in other functions as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM