2011-09-01 36 views
1

我目前正試圖從QWebView接收一些信息,但不幸失敗。從QWebView接收表單信息

如何找出用戶在表單中更改了哪些字段?可能有幾個包括我不感興趣的隱藏的內容,我只想要關於哪些內容被用戶更改的信息。 (其中一種方法是使用evaluateJavaScript()列出所有表單和輸入並稍後檢查它們,但這很難看,並且對第二個問題沒有幫助)

另外我想知道表單本身的信息。什麼是名稱,方法和行動?

QWebPage目前只提供了一個覆蓋acceptNavigationRequest()類型的NavigationTypeFormSubmitted,它不能幫助我,因爲它不會給我任何這些信息。

謝謝你的幫助!

回答

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