Hello all,
I have a very large program. It uses WebSockets and in general it is working well.
I’ve found I have a need to create a temporary popup with an error message. Something like “That item is not available”. At the point where I identify this case, I am in the middle of function, building an Array which will go to Notify users.
There will be instances when there are 2 remote users, therefore the popup needs to go to both.
I’ve looked at various sources, but the haven’t really found a solution.
An alternative may be to change a color on the page that WS is updating, but I don’t know how to do that either (8-(
Any suggestions?
Hi.
Have you taken a look at the window.alert() Javascript function? https://www.w3schools.com/js/js_popup.asp
Regards,
Sara
I’ve looked at that and will try it. But how does the C code talk to JS?
For example:
if (x>3) { …cause popup error message… }
There must be a js name to call or similar?
Hi.
First, you need a way to send that value to the client.
I think the best way is to use server-sent events because that way you don’t need a request from the client.
So, for example,
if (x>3) { run the code to send the x value or a message to the client. }
To learn more about server-sent events, you can take a look at this example:
The main lines of code are:
- Before the setup(), you need to create an AsyncEventsource:
AsyncEventSource events("/events");
- Set up an event source on setup():
// Handle Web Server Events events.onConnect([](AsyncEventSourceClient *client){ if(client->lastId()){ Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId()); } // send event with message "hello!", id current millis // and set reconnect delay to 1 second client->send("hello!", NULL, millis(), 10000); }); server.addHandler(&events);
- Send the event like this when x>3:
events.send(String(YOUR_VALUE_OR_MESSAGE).c_str(),"EVENT_NAME",millis());
To catch those values on JavaScript take a look at the JavaScript section in the tutorial.
Basically, you’ll need to call the command to create a pop-up window when the javascript receives your event.
Try it out and let me know if you need further help.
Regards,
Sara