Call Javascript Functions from C/C++

If you have ever wondered how to control QWebView’s contents using C/C++, it’s actually pretty easy to accomplish using Qt. All you need to do is to write a Javascript function in your HTML page that does whatever that you need, and evaluate the Javascript function from C/C++.

For example, you wrote a Javascript function in your HTML page, like so:

<html>
<head>
<script type="text/javascript">
function MyFunction()
{
     DoSomething();
}
</script>
</head>
</html>

Then, in C/C++ you can simply call:

myWebView->page()->mainFrame()->evaluateJavaScript("MyFunction();");

That’s all! Once you called evaluateJavaScript() function, Qt will handle the rest for you.

If you want to learn how to call C/C++ functions from Javascript, read this.

Call C/C++ Functions from Javascript

It’s possible to call a C/C++ functions from Javascript through web view. At the moment it will only work in Qt Form and doesn’t work well in QML yet. This will probably change in the future versions.

The first thing you need to do is to add your Qt object to the web view as a Javascript object. Then, connect the main frame’s javaScriptWindowObjectCleared() signal to a custom function which adds your Qt object to Javascript:

connect(ui-&gt;webView-&gt;page()-&gt;mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(addMyObjectToJavascript()));

This step is very important because you don’t want to lose your object when the page is refreshed. This will ensure that the web view re-adds your object if the page ever gets refreshed.

Next, define the function that gets called when the page is loaded or refreshed:

void MainWindow::addMyObjectToJavascript()
{
    ui-&gt;webView-&gt;page()-&gt;mainFrame()-&gt;addToJavaScriptWindowObject("mainWindow", this);
}

In this example, I added the main window to the web view. You can add anything to the web view as long as it’s a class that inherits from QObject.

Before you start calling your C/C++ function from Javascript, you have to make sure the C/C++ function is set to invokable in your header file:

Q_INVOKABLE void doSomething();

Now, you can call the function from Javascript by simply calling:

mainWindow.doSomething();

It’s all that simple.

You can also call Javascript functions from C/C++. Click here to learn how.