Tutorial Qt JavaScript Bridge

dila

New member
In Qt, you can create a QWebView widget, which is a Webkit web page control. Here you can display arbitrary HTML, either using the webView->setHTML(...) method, or using webView->setUrl(...) method and load content from the internet or local file system.

In your HTML you can write JavaScript routines that call back into the Qt applications slot functions, and run native code, all through the comfort of JavaScript! This is known as the Qt WebKit Bridge.

Here is an example application:

F3VtkXh.png


Here is the constructor of the QMainWindow class in the application in the screenshot above:

Code:
#include <QVBoxLayout>
#include <QWebFrame>
#include <QUrl>
#include <QDir>
 
Window::Window() {
  setCentralWidget(new QWidget(this));
  QVBoxLayout* layout = new QVBoxLayout(centralWidget());
 
  view_ = new QWebView(this);
  layout->addWidget(view_);
 
  QString index = QDir::currentPath() + QDir::separator() + "index.html";
  view_->setUrl(QUrl::fromLocalFile(index));
 
  QWebFrame* frame = view_->page()->mainFrame();
  frame->addToJavaScriptWindowObject("myHook", this);
 
  show();
}

Here I have exposed the QMainWindow class itself as the bridge object, but in a bigger application you would probably want a dedicated QObject to serve as a JavaScript interface to protect the rest of your application from JavaScript related logic.

Code:
#include <QMessageBox>
 
void Window::myApplicationCallback(QString message) {
  QMessageBox::information(this, "Information", message);
}

This is a regular Qt slot function, and is accessible from the JavaScript running in the QWebView widget through the window.myHook.myApplicationCallback(...) method.

HTML:
<html>
<p>this is the index page</p>
<script>
  var message = "hello world";
  window.myHook.myApplicationCallback(message);
</script>
</html>

I hope you find this tutorial useful :)

dila
 

Storm Shadow

Administrator
Staff member
Developer
Ida Pro Expert
Elite Cracker
This is very informativ.
Also that you can load local html.Gives many posibilities.
Im gonna play some with this.
thx for sharing this goodie.
 

dila

New member
Hi StormShadow, glad you think it will be useful :p

The only downside is that the Qt WebKit DLL is very big. But if you are not worried about the size of your binaries, then it's great :)
 

Storm Shadow

Administrator
Staff member
Developer
Ida Pro Expert
Elite Cracker
I sometimes takes siterips of interesting sites.Then i was looking for a way to display them locally within a app.This could help out.
 
Top