The following example shows how to write a simple Web application that uses the Browser’s DOM functionalities. Check our for example clientlib.h for a glance of the Web API forward declared in the client namespace using Cheerp.
Save it as dom1.cpp and compile it (how? /opt/cheerp/bin/clang++ -O3 dom1.cpp -o dom1.js)
Now embed it in a web page like:
and open it with your favourite browser.
As you can see the text should have been Boring static text but has been replaced by our script.
Using callbacks
Let’s extend the previous program to revert the original text after 3 seconds.
Interoperability with JavaScript code
Cheerp is designed to offer lightweight, bidirectional interoperability between C++ and JavaScript code. Let’s see how you call JavaScript code from C++
Modify example.html to include and use jQuery
Let’s use the JavaScript changeTitle function from C++
When declaring JavsScript methods in C++ you can use the following data types:
client::String as const references or pointers when using them as parameters and as pointers when returning them (e.g. client::String* concatStrings(const String& a, const String& b))
float, double and integer types
Pointers to C++ objects, to use them you still need to pass them back to C++ code.
C++ lambdas and functions as callback parameters. You need to use the client::EventListener* as the parameter type. (e.g. void addCallback(client::EventListener* callback)). In this case you need to use the cheerp::Callback bridge function as shown in the example above.
Directly invoking JavaScript code
You can also use the __asm__ keyword to inline JavaScript code in the middle of C++ code
Invoking C++ code from JavaScript using the [[jsexport]] attribute
Cheerp makes it possible to allocate and use whole C++ classes from JavaScript. This is done using the [[jsexport]] class attribute.
We also need to modify the HTML page to interact with the jsexport-ed class
As you can see you are free to allocate a new JsBridge object in JavaScript and use it directly.
Using complex browser APIs
We will show how to use XMLHttpRequest to retrieve a file. Please note that Chrome blocks XMLHttpRequests to local files so you need to run the example using Firefox or start a local web server.