Callbacks
Handle commands and messages sent from the WebSerial terminal with the onMessage callback, as a String or as raw bytes.
WebSerial provides a single callback, onMessage(). It notifies your firmware whenever a user sends a command or message from the terminal input bar. If no callback is registered, received messages are discarded.
onMessage()
Register the callback in setup(). You can receive messages either as a String or as a byte buffer.
Only one callback is active at a time. If you register both variants, the callback registered last takes precedence.
Receive messages as a String
WebSerial.onMessage([](const String& msg) {
Serial.println(msg);
});The String variant is invoked only for non-empty messages.
Receive messages as raw bytes
WebSerial.onMessage([](uint8_t *data, size_t len) {
Serial.printf("Received %u bytes from WebSerial: ", len);
Serial.write(data, len);
Serial.println();
});Prop
Type
Callback types
| Type | Definition |
|---|---|
WSLMessageHandler | std::function<void(uint8_t *data, size_t len)> |
WSLStringMessageHandler | std::function<void(const String& msg)> |
Example
The following callback parses simple commands and responds in the terminal:
WebSerial.onMessage([](const String& msg) {
if (msg.startsWith("uptime")) {
WebSerial.printf("Uptime: %lums\n", millis());
} else if (msg.startsWith("ip")) {
WebSerial.println(WiFi.localIP());
} else {
WebSerial.println("Unknown command: " + msg);
}
});The terminal appends a null byte (\0) to each message, and this byte is included in len and in the String. Compare commands with startsWith() or strip the trailing null byte before using ==.
In WebSerial Pro, the callback is not invoked while the input bar is disabled. See Toggle Input.