从QWebView接收表单信息

时间:2011-09-01 12:13:40

标签: forms qt webkit qtwebkit

我目前正在尝试从QWebView接收一些信息,但遗憾的是失败了。

如何找出用户在表单中更改的字段?可能有几个包括我不感兴趣的隐藏的,我只想知道哪些被用户改变了。 (一种方法是使用evaluateJavaScript()列出所有表单和输入,然后再检查它们,但这很难看,并且对第二个问题没有帮助)

另外,我想知道有关表单本身的信息。名称,方法和行动是什么?

QWebPage目前仅提供带有NavigationTypeFormSubmitted类型的acceptNavigationRequest()覆盖,这对我没有帮助,因为它没有给我任何这些信息。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

好的,在阅读了一些“相关”问题之后,我最终发现唯一的方法可能是JavaScript。

我的解决方案如下。更改网站上的数据后,m_changedInputs包含有关哪些表单和哪些输入已更改的信息。

CustomWebPage::CustomWebPage(QWidget *parent)
: QWebPage(parent)
{
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(onLoadFinished(bool)));
}

...

void CustomWebPage::onLoadFinished(bool ok)
{
    // Do nothing on fail
    if ( !ok )
        return;

    // Clear all cached data
    m_changedInputs.clear();

    // Get the main frame
    QWebFrame* frame = mainFrame();
    frame->addToJavaScriptWindowObject("pluginCreator", this);

    // Find the form
    QWebElementCollection forms = frame->findAllElements("form");

    // Iterate the forms
    foreach(QWebElement form, forms) {
        // Determine the name of the form
        QString formName = form.attribute("name");

        // Find the forms' input elements
        QWebElementCollection inputs = form.findAll("input");

        // Iterate the inputs
        foreach(QWebElement input, inputs) {
            input.setAttribute("onchange", QString("pluginCreator.onInputChanged(\"%1\", this.name);").arg(formName));
        }
    }
}

void CustomWebPage::onInputChanged(const QString& formName, const QString& inputName)
{
    qDebug() << "Form (" << formName << ") data changed:" << inputName;

    // Make sure we only have each input once. A QSet would also do the trick.
    QStringList& inputNames = m_changedInputs[formName];
    if ( !inputNames.contains(inputName) )
        inputNames.append(inputName);
}