caoxiemeihao / nuxt-electron

Integrate Nuxt and Electron
MIT License
169 stars 18 forks source link

[BUG] contextBridge #67

Closed angelhdzmultimedia closed 4 months ago

angelhdzmultimedia commented 5 months ago

Environment

OS: Windows 11 Home 10.0.22621 Build 22621 Shell: PowerShell Core 7.3.11 pnpm: 8.14.1 npm: 10.2.3 "electron": "^28.1.4", "electron-builder": "^24.11.0", "nuxt": "^3.9.3", "nuxt-electron": "^0.7.0", "vite-plugin-electron": "^0.28.0", "vite-plugin-electron-renderer": "^0.14.5", "vue": "^3.4.15", "vue-router": "^4.2.5"

Describe Issue

I followed everything in the docs, read the example, searched in the Issues, searched videos on YouTube and watched them, and couldn't find anything that helped me solve this issue.

I used contextBridge, and when sending the command I get an error in the browser and the console.log of the command in electron/preload.ts doesn't get executed.

Yes I added preload in nuxt.config.ts:

electron: {
    renderer: {},
    build: [
      {
        // Main-Process entry file of the Electron App.
        entry: 'electron/main.ts',

      },
      {
        entry: 'electron/preload.ts',
        onstart(options) {
          options.reload()
        }
      }
    ],
  },

image

Was about to give up, until I remembered I have a working electron app made with Quasar/Vue/TypeScript which sends commands using contextBridge, so decided to make a quasar app, moved the nuxt-electron code to the corresponding places (src-electron in quasar project), and it worked right away! image

Any info will be appreciated. 🔥💙💚🤝

angelhdzmultimedia commented 4 months ago

Update

I finally know what's happening but not how to solve it. electron/preload.ts is not being loaded, even though I added it to the build option in nuxt config. I added a console.log in both electron/main.ts and electron/preload.ts, and only the electron/main.ts logs.

angelhdzmultimedia commented 4 months ago

Solved

Had to load the electron/preload.ts at runtime in electron/main.ts as dist-electron/preload.js and pass it to the webPreferences of the BrowerWindow Electron.BrowserWindowConstructorOptions... who knew? 🤷‍♂️

https://github.com/caoxiemeihao/nuxt-electron/blob/main/examples/quick-start/electron/main.ts

Thanks that I went to the example one more time before giving up, I could finally solve this.

Anyone else facing this, remember this module only builds files and modify options, not loads anything, so we have to tell Nuxt to load the built main.ts and tell main.ts to load the built preload.ts. ✌️💚👀🤯