Skip to content

Webview

1
2
3
4
5
6
FetchContent_Declare(
        webview
        GIT_REPOSITORY https://github.com/webview/webview.git
        GIT_TAG 50e4bcc420abdc7be96a54b7c79934a000b76901
)
FetchContent_GetProperties(webview)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if (NOT webview_POPULATED)
    # Library does not have a CMake build script
    # We have to do it ourselves
    FetchContent_Populate(webview)
    add_library(webview INTERFACE)
    target_sources(webview INTERFACE ${webview_SOURCE_DIR}/webview.h)
    target_include_directories(webview INTERFACE ${webview_SOURCE_DIR})

    # Set compile options
    # See: https://github.com/webview/webview/blob/master/script/build.sh
    if (WIN32)
        target_compile_definitions(webview INTERFACE WEBVIEW_EDGE)
        # See: https://github.com/webview/webview/blob/master/script/build.bat
        target_link_libraries(webview INTERFACE "-mwindows -L./dll/x64 -lwebview -lWebView2Loader")
        # target_compile_options(...) ?
    elseif (APPLE)
        target_compile_definitions(webview INTERFACE WEBVIEW_COCOA)
        target_compile_definitions(webview INTERFACE "GUI_SOURCE_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}\"")
        target_compile_options(webview INTERFACE -Wno-all -Wno-extra -Wno-pedantic -Wno-delete-non-abstract-non-virtual-dtor)
        target_link_libraries(webview INTERFACE "-framework WebKit")
    elseif (UNIX)
        target_compile_definitions(webview INTERFACE WEBVIEW_GTK)
        target_compile_options(webview INTERFACE -Wall -Wextra -Wpedantic)
        target_link_libraries(webview INTERFACE "$(pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0)")
    endif ()
endif ()

1
2
add_executable(webview_hello webview_hello.cpp)
target_link_libraries(webview_hello PUBLIC webview)

Share Snippets


1
#include <webview.h>

1
2
3
4
webview::webview w(true, nullptr);
w.set_title("Example");
w.set_size(480, 320, WEBVIEW_HINT_NONE);
w.set_size(180, 120, WEBVIEW_HINT_MIN);

1
2
3
4
w.bind("noop", [](std::string s) -> std::string {
    std::cout << s << std::endl;
    return s;
});

1
2
3
4
5
w.bind("add", [](std::string s) -> std::string {
    auto a = std::stoi(webview::json_parse(s, "", 0));
    auto b = std::stoi(webview::json_parse(s, "", 1));
    return std::to_string(a + b);
});

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
  w.navigate(R"(data:text/html,
  <!doctype html>
  <html>
    <body>hello</body>
    <script>
      window.onload = function() {
        document.body.innerText = `hello, ${navigator.userAgent}`;
        noop('hello').then(function(res) {
          console.log('noop res', res);
        });
        add(1, 2).then(function(res) {
          console.log('add res', res);
        });
      };
    </script>
  </html>
)");

1
w.run();

Share Snippets