2010-09-12 28 views
2

請注意,我是Qt開發的完整初學者。如何在QWebView中通過C++激發JavaScript事件

我有一個QObject添加到JavaScript窗口對象的QObject。 如何在該對象上觸發JS事件?

view->page()->mainFrame()->addToJavaScriptWindowObject(objName,obj); 

我希望能夠使用addEventListener監聽事件。

window.objName.addEventListener('customEventName',function(e){ ... }); 

感謝您的任何幫助。

回答

3

你不能那樣做。只有DOM樹中的節點才能觸發事件,並且注入的對象不是節點。我建議你考慮使用信號插槽機制。您可以在JS連接槽的信號,你會在你的C被髮射++代碼:

window.objectName.signalName.connect(slot); 

插槽僅僅是一個JS的功能,你會在你的代碼的JS部分聲明:

function slot(arg1, arg2, ...) 
{ 
} 

它需要在信號的簽名中聲明的參數。

0

在最近的一個項目中,我使用了以下技術:

void VideoWebPage::urlLoaded(bool ok) 
{ 
    static const QString javascript = 
     "function installCallbacks()         " \ 
     "{                 " \ 
     " var videoTags = document.getElementsByTagName('object');  " \ 
     " for (var i = 0; i < videoTags.length; ++i)      " \ 
     " {                " \ 
     "  if (videoTags[i].type == 'application/x-qt-plugin')  " \ 
     "  {               " \ 
     "   if (videoTags[i].playing)        " \ 
     "   {              " \ 
     "    videoTags[i].playing.connect(playingSlot); " \ 
     "   }              " \ 
     "  }               " \ 
     " }                " \ 
     "}                 " \ 
     \ 
     "function playingSlot(videoId)        " \ 
     "{                 " \ 
     " var playEvent=document.createEvent('Events');     " \ 
     " playEvent.initEvent('play', true, false);      " \ 
     " document.getElementById(videoId).dispatchEvent(playEvent); " \ 
     "}                 " \ 
     "installCallbacks();           "; 
    mainFrame()->evaluateJavaScript(javascript); 
} 

這個方法查找所有<object>標籤和playing信號連接到JavaScript函數playingSlot()playingSlot()函數依次創建名稱爲playEvent對象,並將其作爲普通DOM事件進行分派。然後 HTML文件看起來像:

<html> 
<head> 
<script language="text/javascript"> 
    void init() 
    { 
     document.getElementById('id1').addEventListener('play', onPlay); 
    } 
    void onPlay(event) 
    { 
     alert('playing'); 
    } 
</script> 
</head> 
<body onload='init()'> 
    <object id='id1' type='application/x-qt-plugin'> 
    </object> 
</body> 
</html> 

這當然是使用Qt的插件小工具的工作。我沒有用純HTML進行測試(即沒有使用Qt插件的地方)。

相關問題