Igloczek / astro-electron

Build cross-platform desktop apps with Astro and Electron
9 stars 1 forks source link

When trying to open 2 windows, the second window cannot load any content #1

Open kuworking opened 4 days ago

kuworking commented 4 days ago

By using astro simplest installation, and then installing astro-electron, this works as expected.

But, if trying to have 2 windows, it doesn't

// src/electron/main.ts
import * as url from "url";
import { app, BrowserWindow } from "electron";

app.whenReady().then(() => {
  const win = new BrowserWindow({
    title: "Main window",
    webPreferences: {
      preload: url.fileURLToPath(new URL("preload.mjs", import.meta.url)),
    },
  });

  const win2 = new BrowserWindow({
    title: "Main window 2",
    webPreferences: {
      preload: url.fileURLToPath(new URL("preload.mjs", import.meta.url)),
    },
  });

  // You can use `process.env.VITE_DEV_SERVER_URL` when the vite command is called `serve`
  if (process.env.VITE_DEV_SERVER_URL) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL);
    win.webContents.openDevTools();
  } else {
    // Load your file
    win.loadFile("dist/index.html");
    win2.loadFile("dist/index.html");
  }
});

The first message that I see is Not allowed to load local resource: file:///Users/.../dist/index.html

When disabled with

      webPreferences: {
        webSecurity: false,

Then I do not have any error message, but win2 appears blank while win works as expected.

Igloczek commented 2 days ago

Hi, thanks for reporting this.

I've tested this in my app, and works just fine, both in dev and prod.

What Electron version are you using? I'm still on v28, maybe that's why it works.

kuworking commented 1 day ago

In my case I couldn't make it work. Then I just moved the integration directly to my astro.config, and now they open well. I would say this doesn't make sense, if it works now for me, it should have worked before, but I did try (before opening this issue) and I wasn't able.

Yes, all package versions are updated, but again, it doesn't make sense. Let's close it and say it never happened (and big thanks for your repository!)

My package.json:

{
  "name": "xxx",
  "type": "module",
  "version": "2.0.0",
  "main": "dist-electron/main.js",
  "scripts": {
    "test": "electron .",
    "dist": "electron-builder",
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "build": {
    "appId": "xxx.app",
    "productName": "xxx",
    "compression": "store",
    "asar": "false",
    "directories": {
      "output": "out",
      "buildResources": "dist"
    },
    "dmg": {
      "title": "${productName} ${version}"
    }
  },
  "dependencies": {
    "@astrojs/react": "3.6.0"
  },
  "devDependencies": {
    "astro": "4.11.3",
    "electron": "31.1.0",
    "electron-builder": "24.13.3",
    "eslint": "9.6.0",
    "eslint-config-prettier": "9.1.0",
    "eslint-plugin-prettier": "5.1.3",
    "eslint-plugin-astro": "1.2.2",
    "prettier": "3.3.2",
    "prettier-plugin-astro": "0.14.0",
    "vite-plugin-electron": "0.28.7"
  }
}

My astro.config.mjs

import { defineConfig } from 'astro/config'
import react from '@astrojs/react'
import vitePluginElectron from 'vite-plugin-electron/simple'
import path from 'path'

// https://astro.build/config
export default defineConfig({
  integrations: [
    react(),
    {
      name: 'xxx',
      hooks: {
        'astro:config:setup': ({ config, command, updateConfig }) => {
          if (command === 'build') {
            updateConfig({
              base: '/astro-electron',
            })
          }
          updateConfig({
            vite: {
              plugins: [
                vitePluginElectron({
                  main: {
                    entry: 'src/electron/main.js',
                    vite: config.vite,
                  },
                  preload: {
                    input: 'src/electron/preload.js',
                    vite: config.vite,
                  },
                  renderer: undefined,
                }),
              ],
            },
          })
        },
        'astro:build:done': async ({ dir, routes }) => {
          await Promise.all(
            routes.map(async route => {
              const file = fs.readFileSync(route.distURL, 'utf-8')
              const localDir = path.dirname(route.distURL.pathname)
              const relativePath = path.relative(localDir, dir.pathname)
              fs.writeFileSync(route.distURL, file.replaceAll(/\/(astro-electron|public)/g, relativePath || '.'))
            })
          )
        },
      },
    },
  ],
  build: { format: 'file' },
})

main.js

import * as url from 'url'
import { app, BrowserWindow } from 'electron'

const isDev = !app.isPackaged || process.env.NODE_ENV == 'development'

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    title: 'xxx1',
    width: 1800,
    height: 1600,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      contextIsolation: true,
      sandbox: false,
      preload: url.fileURLToPath(new URL('preload.mjs', import.meta.url)),
    },
  })

  if (process.env.VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
  } else {
    mainWindow.loadFile('dist/xxx1.html')
  }

  if (isDev) {
    const secondWindow = new BrowserWindow({
     title: 'xxx2',
      width: 1800,
      height: 1600,
      webPreferences: {
        webSecurity: false, // I got an error and I had to deactivate it
        nodeIntegration: true,
        enableRemoteModule: true,
        contextIsolation: true,
        sandbox: false,
        preload: url.fileURLToPath(new URL('preload.mjs', import.meta.url)),
      },
    })

    if (process.env.VITE_DEV_SERVER_URL) {
      secondWindow.loadURL(process.env.VITE_DEV_SERVER_URL)
    } else {
      secondWindow.loadFile('dist/xxx2.html')
    }

    secondWindow.webContents.openDevTools()
    mainWindow.webContents.openDevTools()
  }
}