[Qt-interest] returning a QObject to javascript in WebKit

Paul Dixon lordelph at gmail.com
Wed Jun 3 22:34:59 CEST 2009


> I've  added an object to a QWebFrame with addToJavaScriptWindowObject,
> and successfully called a slot on that object from javascript.
>
> I'm having trouble getting that slot to return a new object.
> (snip!)


One rather ugly hack I'm now considering is to use
addToJavaScriptWindowObject to drop the object I want to return into
the window object with a random name, then have my slot return the
name of the object instance instead:

QString MyApp::helloWorld()
{
     //general a unique name for the js variable
     QString name=getRandomVariableName();

     //here's the object we want to expose to js
     MyObject* pReturn=new MyObject();

     //we make attach our object to the js window object
     getWebFrame()->addToJavaScriptWindowObject(name, pReturn,
         QScriptEngine::ScriptOwnership);

     //tell js the name we used
     return name;
}

The JS can be written to check if the return value is a string, and if
it is, grab the object from the window.:

var foo=myapp.helloWorld();
if (typeof foo == "string")
{
    foo=window[foo];
}

A little ugly, but will get me by until a better method comes along. I
see in the roadmap that future Qt versions are going unify the
scripting support so that it's all based on the JavaScriptCore in
WebKit, so hopefully this will improve then!




More information about the Qt-interest-old mailing list