qt webview与js交互(网页里的弹出窗口不响应js接口)
步骤:
QWebView *pWebView = new QWebView();
pWebView->load(QUrl(yourHtml));
//yourHtml 为网址或本地资源地址,如果放在qt资源里则html地址前要加qrc:前缀。
pWebView->page()->settings()->setAttribute(QWebSettings::JavascriptEnabled,true);
//QWebSettings::JavascriptEnabled Enables or disables the running of JavaScript programs. This is enabled by default
pWebView->page()->mainFrame()->addToJavaScriptWindowObject("bound",this);
//bound在html文件中设定。
connect(pWebView->page()->mainFrame(),SIGNAL(javaScriptWindowObjectCleared()),this,SLOT(slot_AddObjectToJs()));
//If you intend to add QObjects to a QWebFrame using addToJavaScriptWindowObject(), you should add them in a slot connected to this signal. This ensures that your objects remain accessible when loading new URLs.
...
void slot_AddObjectToJs()
{
pWebView->page()->mainFrame()->addToJavaScriptWindowObject("bound",this);
}
//------------------------------------------------------------------------------------------------------------------------------------------------
只有一个frame的网页用以上步骤即可,但是有的网页里会弹出新的网页(比如网页里的弹窗),此时此弹窗里的js接口函数就访问不到了。这是因为page()中添加新frame的后没有绑定(addToJavaScriptWindowObject("bound",this))。还需添加
connect(pWebView->page(),SIGNAL(frameCreated(QWebFrame*)),this, SLOT(slot_frameCreated(QWebFrame*)));
//frameCreated(QWebFrame*) This signal is emitted whenever the page creates a new frame.
void slot_frameCreated(QWebFrame* pWebFrame)
{
pWebFrame->addToJavaScriptWindowObject("bound", this);
}
//这样不管加载的html页面刷新还是有新frame打开都能正常调用js借口函数。
//-------------------------------------------------------------------------------------------------------------------------------------------------
webview --> webpage --> webFrame 关系
addToJavaScriptWindowObject("bound",this);
/*
Make object available under name from within the frame's JavaScript context. The object will be inserted as a child of the frame's window object.
Qt properties will be exposed as JavaScript properties and slots as JavaScript methods. The interaction between C++ and JavaScript is explained in the documentation of the Qt WebKit bridge.
If you want to ensure that your QObjects remain accessible after loading a new URL, you should add them in a slot connected to the javaScriptWindowObjectCleared() signal.
*/
参考:qthelp <The Qt WebKit Bridge>