webview / webview

Tiny cross-platform webview library for C/C++. Uses WebKit (GTK/Cocoa) and Edge WebView2 (Windows).

Home Page:https://webview.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass a javascript function as an arg to C/C++?

rcorre opened this issue · comments

What OS are you using (uname -a, or Windows version)?

Darwin MLH6TM47JW6G 23.0.0 Darwin Kernel Version 23.0.0: Fri Sep 15 14:43:05 PDT 2023; root:xnu-10002.1.13~1/RELEASE_ARM64_T6020 arm64

What programming language are you using (C/C++/Go/Rust)?

clang version 14.0.6

What did you expect to see and what you saw instead?

Is it possible for javascript to pass a callback function to c/c++? I'd like to have javascript subscribe to an event in C++, and C++ invokes the provided callback.

webview::webview w( false, nullptr );
w.set_title( "Basic Example" );
w.set_size( 480, 320, WEBVIEW_HINT_NONE );
w.set_html( html );
w.bind( "notify",
        []( const std::string& req ) -> std::string
        {
            std::cout << "Got request " << req << std::endl;
            return "";
        } );
w.run();
window.notify( function () { } );

The C++ outputs Got request [null]

On the JS side this would attempt to serialize the function and transfer it to the C++ side but that can't be done. Special handling would be needed.

You can instead make a function in JS and use w.eval() to call it from C++.