Logging Console Messages

You can get log output for JavaScript errors, network errors, and more to help diagnose issues when writing code for your View.

Attaching the ViewListener Interface

You can use the ViewListener::OnAddConsoleMessage event to handle console messages.

You should subclass ViewListener and handle the OnAddConsoleMessage() event. Then bind your class to a View via View::set_view_listener().


See the API declaration for ViewListener here.

Here's an example that logs these messages to std::cout:

#include <Ultralight/Ultralight.h>
#include <iostream>
using namespace ultralight;
inline std::string ToUTF8(const String& str) {
  String8 utf8 = str.utf8();
  return std::string(utf8.data(), utf8.length());

inline const char* Stringify(MessageSource source) {
  switch(source) {
    case kMessageSource_XML: return "XML";
    case kMessageSource_JS: return "JS";
    case kMessageSource_Network: return "Network";
    case kMessageSource_ConsoleAPI: return "ConsoleAPI";
    case kMessageSource_Storage: return "Storage";
    case kMessageSource_AppCache: return "AppCache";
    case kMessageSource_Rendering: return "Rendering";
    case kMessageSource_CSS: return "CSS";
    case kMessageSource_Security: return "Security";
    case kMessageSource_ContentBlocker: return "ContentBlocker";
    case kMessageSource_Other: return "Other";
    default: return "";

inline const char* Stringify(MessageLevel level) {
  switch(level) {
    case kMessageLevel_Log: return "Log";
    case kMessageLevel_Warning: return "Warning";
    case kMessageLevel_Error: return "Error";
    case kMessageLevel_Debug: return "Debug";
    case kMessageLevel_Info: return "Info";
    default: return "";

// Inherited from ViewListener::OnAddConsoleMessage
// Make sure that you bind 'MyApp' to 'View::set_view_listener'
// to receive this event.
void MyApp::OnAddConsoleMessage(View* caller,
                                MessageSource source,
                                MessageLevel level,
                                const String& message,
                                uint32_t line_number,
                                uint32_t column_number,
                                const String& source_id) {
  std::cout << "[Console]: [" << Stringify(source) << "] [" 
            << Stringify(level) << "] " << ToUTF8(message);
  if (source == kMessageSource_JS) {
    std::cout << " (" << ToUTF8(source_id) << " @ line " << line_number 
              << ", col " << column_number << ")";
  std::cout << std::endl;