How to get QWebFrame for iframe?

You may think it is easy to get the QWebFrame object for an iframe element in a web page since  QWebFrame is formed by iframe/frame(http://doc.qt.io/qt-5/qwebview.html) and there must be a function or method to get the QWebFrame object of the iframe . Unfortunately, it is not a trivial work at present. You can not get the QWebFrame of an iframe based on the id of the iframe, nor can you get QWebFrame from QWebElement of the iframe. QWebFrame has a function childFrames which can list all sub-frames of the main frame. To get the QWebFrame of a particular iframe, you should iterate over all the child frames of the main frame and compare the attributes of the child frames to some specified value to pick your iframe out.  For example, the following code will pick out the iframe whose url contains the string “myiframeurl”;

 

foreach(QWebFrame*childframe,frame->childFrames())
{
if(childframe->url().toString().contains("myiframeurl"))
{
yourframe = childframe;
break;
}
}

You can also select the QWebFrame according to its name(QWebFrame::frameName()). Once you get the QWebFrame of the iframe, you can obtain the whole DOM tree of the QWebFrame by calling frame->documentElement(). If you are not familiar the content of the web page, you may not know the name or url,or other attributes of the  QWebFrame. You can print the values of these attributes in the iteration of the child frames and guess which one is the one you want.

Posted in

Leave a Reply