最近我的一个项目中要用到Webbrowser的插件,针对这个项目,特意学习了一下JavaScript和MsHTML接口,在这里小结一下用法。
首先看下JavaScript,我们先来看个例子。触发A.html页面的iframe框架内容下面所有a标签鼠标经过事件,看文字似乎有点绕,多看几遍就明了了。这里我简单贴A.html页面的内容,好理解一点。
<div class="con_main_con"><iframe id="myframe" style="height: 620px;" src="/b.html" name="myframe" width="100%" height="150" frameborder="0" scrolling="yes"></iframe></div>
然后里面的B.html内容
<a id="123" style="cursor: pointer;"></a>学习
<a id="124" style="cursor: pointer;"></a>学习
<a id="125" style="cursor: pointer;"></a>学习
说明下b.html页面的js_test函数是在鼠标经过的时候触发,这个函数的效果是把A标签添加一个href属性,我现在要做的就是不用鼠标不经过就自动执行该函数,JS实现代码如下:
var as = myframe.document.getElementsByTagName('a');
for (var i = 0; i < as.length; i++) {
as[i].onmouseover();
};
所有的A标签全部触发这个鼠标经过的事件,那么b.html的A标签(包含有这个事件=js_test)全部就有href属性了。这里特别要注意一点,一定只能通过
myframe的document来获取,不然获取到所有的a标签是a.html下面的。那么在VC++中怎么执行JS代码呢?其实很简单,看代码
HRESULT CWebDlg::InvokeJs(CString script)
{
//VC中调用JS脚本
IHTMLDocument2 *m_iHTMLDocument = NULL;
IHTMLWindow2 *m_iHTMLWindow2 = NULL;
m_iHTMLDocument = (IHTMLDocument2 *) m_Explorer.get_Document();
if (m_iHTMLDocument == NULL)
return NULL;
m_iHTMLDocument->get_parentWindow(&m_iHTMLWindow2);
if (m_iHTMLWindow2 == NULL)
return NULL;
VARIANT m_var;
HRESULT h_result = m_iHTMLWindow2->execScript(CComBSTR(script),CComBSTR("JavaScript"), &m_var);
m_iHTMLWindow2->Release();
m_iHTMLDocument->Release();
return h_result;
}
m_Explorer是浏览器activeX插件对象。
最后再贴上用C++代码实现遍历当前页面下所有的iframe方法
IHTMLDocument2 * m_iHTMLDocument = NULL;
m_iHTMLDocument = (IHTMLDocument2 * ) m_Explorer.get_Document();
if (m_iHTMLDocument == NULL)
return;
IHTMLElement * pBody;
m_iHTMLDocument - > get_body( & pBody);
BSTR html; //存放html源代码
pBody - > get_innerHTML( & html);
CComPtr < IHTMLFramesCollection2 > spFramesCollection2;
m_iHTMLDocument - > get_frames( & spFramesCollection2); //获取所有的iframe
long nFrameCount = 0;
HRESULT hr = spFramesCollection2 - > get_length( & nFrameCount);
if (FAILED(hr) || 0 == nFrameCount) return;
for (long i = 0; i < nFrameCount; i++) { CComVariant vDispWin2; hr = spFramesCollection2 - > item( & CComVariant(i), & vDispWin2);
if (FAILED(hr))
continue;
CComQIPtr < IHTMLWindow2 > spWin2 = vDispWin2.pdispVal;
if (!spWin2)
continue;
CComPtr < IHTMLDocument2 > spDocument;
HRESULT hRes = spWin2 - > get_document( & spDocument);
if ((S_OK == hRes) && (spDocument != NULL)) {
IHTMLElement * pBody2;
spDocument - > get_body( & pBody2);
BSTR html2;
pBody2 - > get_innerHTML( & html2);
CString iframeStr(html2);
}
}
本文链接:http://www.it72.com/9439.htm