Send message from JS to Go directly behaves as expected but not if it's initiated by onclick or href
Closed this issue · 4 comments
Hi there!
I am using bootstrap and bundler.
I have a message handler in Go as per below:
// handleMessages handles messages
func handleMessages(_ *astilectron.Window, m bootstrap.MessageIn) (payload interface{}, err error) {
switch m.Name {
case "getVersion":
payload = version
case "getAuthed":
payload = authed
case "doSomething":
doIt(m.payload)
}
return
}
and a couple of JS functions:
function send(t, n, p) {
// This will wait for the astilectron namespace to be ready
console.log("Sending message to go...");
document.addEventListener('astilectron-ready', function() {
// This will send a message to GO
var resp = astilectron.sendMessage({name: n, payload: p}, function(message) {
console.log("received: " + message.payload);
next(t, message.payload);
});
})
}
function next(type, s) {
switch(type) {
case "version":
document.getElementById("version").innerHTML = s;
break;
case "auth_status":
var z = document.getElementById("status");
if (s == true) {
z.innerHTML = "Authorized";
}
break;
case "do_something":
console.log("Do Status: " + s);
break;
}
}
When I call send() directly from index.html with <script> </script> tags, everything works.
However, if I call send() from a button or a link:
<button id="do-something" onclick="send('do_something', 'doSomething', 'something')">Do It!</button>
It does nothing after seeing "Sending message to go..." in console specifically for the cases that call another function in Go. Any ideas on why this is happening?
I feel like this has got to be something super simple that I am missing....
Thanks!
This is normal, your send
function waits for an astilectron-ready
event everytime but this event is sent once at the beginning and that's it.
My advice would be to wrap your whole logic in document.addEventListener('astilectron-ready', function() {
to make sure it's only called once astilectron
is setup, but don't listen to that astilectron-ready
event after that.
That's it! I was just in the middle of looking over your demo and was changing things towards that direction. Thank you!
Works beautifully now! Thanks again!
Cheers