开发者

Receiving form information from QWebView

开发者 https://www.devze.com 2023-04-01 15:44 出处:网络
I\'m currently trying to receive some information from QWebView but unfortunately fail. How do I find out which fields the user did change in a form? There may be several including hidden ones which

I'm currently trying to receive some information from QWebView but unfortunately fail.

How do I find out which fields the user did change in a form? There may be several including hidden ones which I'm not interested in, I only want information about which ones were altered by the user. (One method for this would be to list all forms and inputs with evaluateJavaScript() and check them later, but this is ugly and doesn't help with the second problem)

Also I want to know information about the form itself. What was the name, method 开发者_运维问答and action?

QWebPage currently only provides a override of acceptNavigationRequest() with type NavigationTypeFormSubmitted which doesn't help me as it doesn't give me any of these information.

Thank you for your help!


Ok, after reading some of the "Related" questions here I eventually found that the only way may be JavaScript.

My solution is below. After changing data on the website, m_changedInputs contains information about which forms and which inputs have been changed.

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消