javascriptelectronipcvuejs3ipcrenderer

Send ipcRenderer variable to vue3 page


I have a vue3 app with electron and need to send a variable from the ipcRenderer to my Vue3 page. I cant figure out how to do it especially given vue strips away lots of js. What im trying to do is to save the path of a folder which so far works fine, then display it in the vue3 app either in a span or whatever. I successfully got the value i need to display to the ipcRenderer but cant access it using my vue app.

Vue3 page

          <q-btn
            id="showpath"
            dark
            flat
            size="xl"
            label="show Path"
            type="submit"
            @click="showpath"
          />
        </div>

export default {
  name: "Settings",
  props: {},
  methods: {
    loader() {
      window.postMessage({
        type: "select-dirs",
      });
    },
    showpath() {
      const testa = window.postMessage({ type: "pathtf"})
      console.log("Vue page says :"+ testa)
    },
  },
};
</script>

All I get here is "undefined

Preloader script

const { ipcRenderer } = require('electron');
const settings = require('./settings');

process.once('loaded', () => {
    window.addEventListener('message', evt => {
            if (evt.data.type === 'select-dirs') {
                ipcRenderer.send('select-dirs')

            }

        }),
        window.addEventListener('message', evt => {
            if (evt.data.type === 'pathtf') {
                const pathtf = settings.gettfpath("pathtf")
                console.log(pathtf)
            }

        })
})

The console.log in the preload file works and displays the value, but i cant get that value to my vue3 page.

Any tip? Thank you


Solution

  • I would suggest that you use electron's contextBridge to expose certain methods (send/receive) to the renderer process.

    I do not know what your gettfPath method does but if that variable is available to you in the preloadjs file you should be able to expose it as a variable like so:

    const {contextBridge} = require("electron");
    
    contextBridge.exposeInMainWorld("electronApi", {
      pathtf: settings.gettfPath()
    });
    

    With this your path will be exposed to your renderer process as window.electronApi.pathtf

    Here are two resources you may find helpful:

    1. How to use preload.js properly in Electron
    2. https://medium.com/swlh/how-to-safely-set-up-an-electron-app-with-vue-and-webpack-556fb491b83 (This one may not be exactly what you are looking for but it has a good explanation / example of how to use ipc with view and electron)