In the vue3 template, I'm unable to access global objects exposed by electron preload.js¶
Problem description¶
In my electron app, I used vue3 to build the UI layer. I defined global objects in the preload.js like the official docs do.
But when I try to access those global objects in the vue3 template, error occurs.
Here's the preload.js code example:
const { contextBridge } = require('electron')
contextBridge.exposeInMainWorld('versions', {
node: () => process.versions.node
})
Here's the vue3 template code example:
<template>
node version: {{ window.versions.node() }}
</template>
Then an error occurs, the error message looks like: caught TypeError: Cannot read properties of undefined (reading 'versions')
Cause of the problem¶
Global objects exposed by electron contextBridge.exposeInMainWorld
are actually properties of the global window
object.
However, by default, window
is not accessible in the template of vue.
Solution¶
Edit main.js
of the Vue app, and config app.config.globalProperties
after initialization of app
variable:
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.globalProperties.window = window // notice this line
app.mount('#app')
In the code above, app.config.globalProperties.window = window
makes window
accessible in vue3 template.
This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/electron_vue_window