开发者

QWebPage force to open link in same tab

I'm working on a one tab browser in Qt and I've encountered a problem:

The links on the web that lead to external websites are set to open in a new tab (using taget='_blank'). However, si开发者_高级运维nce my browser has just one tab those links are simply inactive.

I believe that it's possible to force the links to open in the same tab by injecting JavaScript (QWebFrame::eveluateJavaScript), by that seems like an inefficient solution.

Is there a native way in Qt to force all links to open in the same tab/window?

Edit:

I've come up with a native way by re-implementing loadFinished(bool) :

void MyBrowser::loadFinished(bool ok) {
    if (!ok) {
        return;
    }

    QWebFrame* frame = webView->page()->mainFrame();
    if (frame!=NULL) {
        QWebElementCollection collection = frame->findAllElements("a[target=_blank]");
        foreach (QWebElement element, collection) {
            element.setAttribute("target", "_self");
        }
    }
}

If there's an even better way I'd be glad to see it.


Make QWebPage's subclass, and override createWindow(). Most simple way is as follows:

QWebPage* CustomWebPage::createWindow(WebWindowType type)
{
    return this;
}

And, set above webpage to webview like this:

// QWebView Setting
ui->webView->setPage(new CustomWebPage());
ui->webView->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
ui->webView->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜