Qt QWebEngine – work with HTML <a> anchors

  activex, c++, qt, qwebengine, qwebengineview

Good day, stackoverflow community. Have a non-trivial question.

For displaying web content we are using ActiveX. We decided to switch to QWebEngine, but were faced with the problems:

ActiveX allows us:

  1. save HTML anchors in QAxObject
  2. listen to anchors click events
  3. extract and change anchors properties ("id", "href")

Example of code:

CComPtr<IHTMLDocument2> m_htmlDocument;
CComPtr<IHTMLElementCollection> htmlAnchorsCollection;
QSignalMapper m_anchorClickMapper
QList<QPointer<QAxObject>> m_anchors;
...
//Connects the mapping of anchors and the AnchorClicked() signal. Id will be a param
connect(&m_anchorClickMapper, SIGNAL(mapped(QString)), SIGNAL(AnchorClicked(QString)));
...
    
m_htmlDocument->get_anchors(&htmlAnchorsCollection);
...
for (auto i = 0; i < anchor_count; ++i)
{
    CComPtr<IDispatch> disp;
    if (SUCCEEDED(htmlAnchorsCollection->item(CComVariant(i), CComVariant(0), &disp)))
    {
        auto anchor = new QAxObject(disp, this);
        auto id = anchor->property("id").toString();

        //For anchors with an id, listen to click() events and emit AnchorClicked()
        if (!id.isEmpty())
        {
            m_anchorClickMapper.connect(anchor, SIGNAL(onclick()), SLOT(map()));
            m_anchorClickMapper.setMapping(anchor, id);

            m_anchors << anchor;
        }
    }
}

working with anchors

for (auto & anchor : m_anchors)
{
    auto id = anchor->property("id").toString();
    if (id.startsWith("cta"))
    {
        auto href = anchor->property("href").toString();
        
        // adding additional params to href
        
        anchor->setProperty("href", href);
    }
}
                

HTML anchor looks like:

<a class="cta cta-link" id="{{cta_id}}" onclick="window.close()" href="https://www.google.com/" target="_blank">English CTA1</a>

Is it possible to do something similar with QWebEngine?
Key requirements:

  1. Catch anchors click events
  2. Understand, which anchor was clicked (depending on the name we can launch internal C++ logic)
  3. Have a possibility to update anchors href

Will be appreciate for any thoughts/ideas

Source: Windows Questions C++

LEAVE A COMMENT