Search code examples
javascriptqtqwebviewinnertext

How to get DOM innerText on QWebView?


How can I get all of document.body.innerText on QWebView? I use QT version 5.5.1.

For example,

html file to load

<script>
    document.write("hello world!");
</script>

and I want to get "hello world".

so, I tried like this on QT

QWebView *wv = new QWebView(this);
QWebFrame *frame = wv->page()->mainFrame();
frame->load(QUrl("file:// ~ file path ~"));
QString string = frame->toPlainText();
// then write string to file for checking

I expected the string is "hello world" but, there was nothing. I searched and found this link, and I changed code like that, but there was still nothing.

Do I misunderstand toPlainText() perhaps? And how I can get DOM innerText on QT 5.5?


Solution

  • You're not leaving enough time for the page to update. It will take a moment for the HTML to load, let alone for the Javascript to get executed.

    There's a couple of workarounds here:

    1. Use a QTimer to wait a couple of seconds before calling toPlainText(). This is hacky because there's no way of knowing exactly how long to wait, but it would be adequate for demonstration purposes.
    2. Update the Javascript code to send back a notification to your C++ code after document.write() is called. For example, you could do this via a WebSocket, or use Qt WebChannel.