Qt programming: How to extend Javascript API in webkit
I am new to Qt and what I am trying to do is:
- Create a Linux app using the Qt framework.
- This app displays some web pages from the Internet.
- I want to extend the JavaScript API t开发者_Python百科o access some device and device based data, which means some devices can be controlled using JavaScript in Webkit.
But how do I add some customized functions/classes to Webkit in Qt?
Fortunately, there exists some documentation on this, finally: http://doc.qt.io/qt-4.8/qtwebkit-bridge.html
I've done a QWebKit project in which I stablished a bridge between Javascript and my C++ code.
To achieve this I used the method:
this->page()->mainFrame()->addToJavaScriptWindowObject( "god", this );
This allows you to execute methods of the object you pass to addToJavaScriptWindowObject as second parameter from Javascript, using the object specified as first parameter.
Here an example:
class Browser : public QWebView
{
Q_OBJECT
public:
Browser( QWidget* parent=0 )
{
connect( this->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(onJavaScriptWindowObjectCleared()) );
}
public slots:
void onJavaScriptWindowObjectCleared()
{
// QString script = "console.log('init!');";
// this->page()->mainFrame()->evaluateJavaScript( script );
}
void onChange()
{
qDebug() << "Browser::onChange()";
}
}
Then, from Javascript I can do:
$('input:text').keydown( god.onChange );
So every time I press a key in an input box, god.onChange() is executed which executes Browser::onChange() slot.
This way you avoid extending the JS api.
精彩评论