Callback from C++ to Javascript function - QtWebkit
2015-04-12 01:13:31 +0000
This article discusses on how to call a JavaScript function from C++ using
Qt Framework. This framework uses Qt-Webkit. Currently, there are two ways
to achieve this.
Install Signals and Slots for the Javscript function.
Using the in-built API – evaluate JavaScript
Note: The Javascript evaluation by the C++ class will be understood once the
web-page is loaded. Thus, we should add the JavaScript to the window
object, once the web-page is loaded. This can be done by installing the slot
for the signal – javaScript WindowObject Cleared.
Here are the details for each mechanism.
Install signal and slots for the JavaScript function.
a) Add Java script window object to the javaScript WindowObject Cleared slot.
b) Declare a signal in the class.
c) Emit the signal
d) In the Javascript, connect the signal to the Javascript function slot.
Here is the syntax to connect.
Note, you can do a callback to the Javascript only once the webpage is
loaded. This can be done by connecting to the slot emitted by the signal
loadFinished() in the C++ applicat ion.
Let ’s see t he real example now.
Here is the simple form - HTML/JavaScript
Here is the C++,Qt Code.
Using the in-built API – evaluateJavaScript
Here, the C++ class should know the Java Function to call. However, this is not
required in the signal/slot mechanism, which was described earlier. Please see
the steps here.
a) Add Java script window object to the javaScript WindowObject Cleared slot .
b) Invoke t he API from page->mainframe-
evaluate JavaScript (“JavaScript_function()”)
c) In the Javascript , declare the
Javascript windowobject.method_name(“Javascript function name that will be
invoked from this method”);
Here is the sample code.