Reputation: 9502
How to make QML WebView Element use Qt::openUrlExternally instead of some visual newWindowComponent?
Upvotes: 2
Views: 1893
Reputation: 976
The following code will open all links in new windows, but it is trivial to add detection for target=_blank
WebView{
id: webView
url: "samples/sample.html"
preferredWidth: parent.width
enabled: false
onLoadFinished: {
evaluateJavaScript(' \
var els = document.getElementsByTagName("a"); \
for (var i in els){ \
els[i].onclick = function(e){e.preventDefault(); qml.qmlCall(this.getAttribute("href")); return false;} \
} \
')
enabled = true;
}
javaScriptWindowObjects: QtObject {
WebView.windowObjectName: "qml"
function qmlCall(url) {
console.log(url);
Qt.openUrlExternally(url)
}
}
}
It boils down to adding some javascript in the webview after it has loaded to override the default action of links and pass the value of the href
attribute to qml, and open externally from there.
Upvotes: 0
Reputation: 8147
I don't think there is a simple way to do this using QML. You can do this with the standard QWebView
, but there isn't a way to access this functionality from within QML. You would need to re-wrap QWebView
and expose more functions.
An example using the standard C++ interfaces:
test.cpp
#include <QtGui>
#include <QtWebKit>
#include "handler.hpp"
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QWebView view;
view.load(QUrl::fromUserInput("http://qt-project.org/"));
view.page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
LinkHandler handler;
QObject::connect(
&view, SIGNAL(linkClicked(const QUrl&)),
&handler, SLOT(open(const QUrl&)));
view.show();
return app.exec();
}
handler.hpp
#ifndef _HANDLER_HPP_
#define _HANDLER_HPP_
#include <QtGui>
class LinkHandler : public QObject
{
Q_OBJECT
public:
LinkHandler();
public slots:
void open(const QUrl& url);
};
#endif
handler.cpp
#include "handler.hpp"
LinkHandler::LinkHandler() : QObject() {}
void LinkHandler::open(const QUrl& url)
{
QDesktopServices::openUrl(url);
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
find_package(Qt4 4.8 REQUIRED QtCore QtGui QtWebkit)
include(${QT_USE_FILE})
qt4_wrap_cpp(MOC_FILES handler.hpp)
add_executable(test
test.cpp
handler.hpp
handler.cpp
${MOC_FILES})
target_link_libraries(test ${QT_LIBRARIES})
Upvotes: 3