Tracktion / choc

A collection of header only classes, permissively licensed, to provide basic useful tasks with the bare-minimum of dependencies.
Other
543 stars 49 forks source link

How to call JS functions from c++ with choc_WebView.h #24

Closed daveboulden closed 1 year ago

daveboulden commented 1 year ago

I am quite possibly being a bit dim here and so apologies if I am completely missing something crucial, but I am trying to call a JS function in the WebView upon handling an event in the C++ side of things.

Is the only option for call JS functions from C++ to use something like

webview->evaluateJavascript("setSongList({ '1': 'aaa', '2': 'bbb' })");

Currently, it doesn't seem to actually call the function in JavaScript within the WebView. Whereas, doing something like below does work:

webview->evaluateJavascript("alert('I have happened!')");

Am I missing something basic? What I am ultimately trying to do is to call a JavaScript function from C++ with a string containing a JSON structure.

In the library I was using before (https://saucer.github.io/) I could use this function:

saucer::forget(m_smartview->eval<bool>("setSongList({})",newSongs));

but there doesn't seem to be any analogous function within choc_WebView.h

julianstorer commented 1 year ago

Yes - providing a string of javascript to execute is pretty standard, and that's what we do.

I've never used 'saucer' but the eval function you seem to be using there just looks like it builds a javascript string command based on trying to turn some random c++ values into their javascript equivalents..? I guess that's a cute helper function, but in all the places we've needed this, we tended to have our data in a choc::value::Value (which is basically JSON) and then use that, e.g.

        webview.evaluateJavascript ("window.cmaj_deliverMessageFromServer?.(" + choc::json::toString (msg, true) + ");");

Writing a variadic function that turns C++ expressions into javascript is a nice idea, but I've not got time to sidetracked onto it right now, I'm afraid!

daveboulden commented 1 year ago

Thanks Julian, I'll try it again using choc::json::toString().

julianstorer commented 1 year ago

Yeah, that'll do the trick.

Writing a function like the one you mention would be a fun C++ exercise and would make the calling code a little bit shorter, but TBH it wouldn't improve my life enough to be worth it. Maybe someone else will have a go!