asticode / go-astilectron

Build cross platform GUI apps with GO and HTML/JS/CSS (powered by Electron)
MIT License
4.9k stars 344 forks source link

addEventListener #224

Closed lengnuan-v closed 4 years ago

lengnuan-v commented 4 years ago

document.addEventListener('astilectron-ready', function() { // This will send a message to GO astilectron.sendMessage("hello", function(message) { console.log("received " + message) }); })

There is no problem sending data to go through this method, including the refresh can also get the data, but when you click on the route connection, you cannot get the data, why

asticode commented 4 years ago

I don't really understand what your problem is. Can you share some reproducible code ?

lengnuan-v commented 4 years ago
    mounted() {
            document.addEventListener("astilectron-ready", function (event) {
                astilectron.sendMessage({name: "name", payload: "payload"}, function (message) {
                    console.log(message)
                });
            });
    },

Using vue routing, sendMessage is executed. It can only enter the event after the first open or refresh

asticode commented 4 years ago

You only need to wait for astilectron-ready once, when the window first loads. I would create a variable isAstilectronReady = false and would do something like this :

if (!isAstilectronReady) {
  document.addEventListener("astilectron-ready", function (event) {
    isAstilectronReady = true
    astilectron.sendMessage({name: "name", payload: "payload"}, function (message) {
      console.log(message)
    });
  });
} else {
  astilectron.sendMessage({name: "name", payload: "payload"}, function (message) {
    console.log(message)
  });
}
lengnuan-v commented 4 years ago

According to your method is feasible, but the problem will still occur when entering other pages by refreshing other pages. My solution is:

if (typeof astilectron === "undefined") {
    document.addEventListener("astilectron-ready", function (event) {
        astilectron.sendMessage({name: "name", payload: "payload"}, function (message) {
            console.log(message)
        });
    });
} else {
    astilectron.sendMessage({name: "name", payload: "payload"}, function (message) {
        console.log(message)
    });
}
asticode commented 4 years ago

👍

Ghardo commented 4 years ago

just suround the "new Vue" with the event listener

document.addEventListener('astilectron-ready', function() {
  new Vue({
    render: h => h(App)
  }).$mount('#app')
})

or take a look at my vue astilection plugin ;) https://github.com/Ghardo/astor