Qt4:如何通过QtWebkit从C++调用页面中的JavaScript函数?

6 javascript webkit qt4 call qtwebkit

我正在尝试使用Qt4的WebKit端口/实现编写一个简单的日志查看器.我的HTML代码如下所示:

http://pastie.org/613296

更具体地说,我试图找出如何调用add_message()函数,该函数在<script>我的C++代码中的HTML文档的部分中定义.


// Doesn't work:
QWebElement targetElement = chatView->page()->mainFrame()->findFirstElement("head").firstChild("script");

// Function is not included, either...
qDebug() << targetElement.tagName() << targetElement.functions();

// The ultimate attempt in calling the function anyway:
QVariant functionResult = targetElement.callFunction("add_message");
Run Code Online (Sandbox Code Playgroud)

Kam*_*mek 13

如果您使用的是Qt 4.5,请执行以下操作:

htmlView->page()->mainFrame()->evaluateJavaScript("add_message(); null");
Run Code Online (Sandbox Code Playgroud)

注意:null脚本末尾是性能问题.QWebFrame::evaluateJavaScript返回QVariant脚本中的最后一个值.评估脚本中的最后一个值可能非常耗时,因此null最后将其立即返回.