[webkit-dev] Adding Javascript object to Webkit

Michael Goddard michael.goddard at trolltech.com
Thu Apr 3 17:44:40 PDT 2008


Hello Lee,

On Thursday 03 April 2008 20:01, Lee Ka Yuk wrote:
> I'm using the WebKit project for webpage rendering on Qtopia.
> I would like to add some Javascript objects that can be accessed in the
> webpage and implemented with C/C++.

If you are using the latest Qt/4.4 snapshot, the "Qt" way to do it is to use 
the QWebFrame::addToJavaScriptWindowObject(const QString &name, QObject 
*object) function.

For example: (not compiled :) 

class MyObject : public QObject {
    Q_OBJECT
public:
    MyObject() : mVar(0) {}
    int var() {return mFoo;}
    void setVar(int foo) {mFoo = foo;}
   Q_PROPERTY(int var READ foo WRITE setFoo);

public slots:
   int doSomething(int seed)
   {
	return seed * 2;
   }
private:
	int mVar;
};

... later ...
   MyObject* foo = new MyObject();
   myFrame->addToJavaScriptWindowObject("foo", foo);

.. still later [C++] ...
   qDebug() << foo->var() << foo->property("var").toInt();
   qDebug() << foo->doSomething(21);

.. or [javascript] ...
  window.alert("foo.var is:" + foo.var);
  window.alert("foo.doSomething(21) is:" + foo.doSomething(21));

If you're using Qt/4.4 for WebKit, the JSCore functions are not exposed 
through the Qt library, so this is the only way to do what you'd like.

It's up to you to manage the lifetime of the C++ object - once it is deleted, 
if the JS object still exists, accessing member variables and functions will 
throw a JS exception.

Cheers,
MichaelG


More information about the webkit-dev mailing list