我完全不熟悉使用浏览器帮助程序对象开发 IE 扩展。
我设法创建了一个 BHO,它成功地在 HTML 页面的头部插入了一个引用 javascript 文件的脚本标签(参见下面的代码)。
但脚本标记只是位于 DOM 中,外部 javascript 文件未执行。
有没有办法告诉浏览器运行外部javascript文件?
谢谢!
代码详细信息: 我在 OnDocumentComplete 事件上调用了以下方法:
void CHelloWorldBHO::InsertScriptTag(IDispatch* pDispDoc)
{
HRESULT hr = S_OK;
// query for an HTML document.
CComQIPtr<IHTMLDocument3> pDocument3 = pDispDoc;
CComQIPtr<IHTMLDocument2> pDocument2 = pDispDoc;
if (pDocument2 != NULL && pDocument3 != NULL)
{
// ********************** create our script tag Element (pHtmlElem) ****************************
IHTMLElement* pHtmlElem;
CComVariant vAlert="http://www.gnpcb.org/esv/share/js/?action=getDailyVerse"; // example referencing external JS code
CComVariant vJavascript="text/javascript";
hr = pDocument2->createElement(_T("script"), &pHtmlElem);
if (SUCCEEDED(hr) && pHtmlElem != NULL)
{
hr = pHtmlElem->setAttribute(_T("type"), vJavascript);
hr = pHtmlElem->setAttribute(_T("src"), vAlert);
}
// ********************** insert Element (pHtmlElem) in HTML Head ****************************
// Get the head from the DOM.
static const CComBSTR sbstrHead(L"head");
CComPtr<IHTMLElementCollection> objects;
hr = pDocument3->getElementsByTagName(sbstrHead, &objects);
if(SUCCEEDED(hr) && objects != NULL)
{
// Get the number of elements in the collection.
long nElements = 0;
hr = objects->get_length(&nElements);
if (hr == S_OK && nElements > 0)
{
CComVariant svarItemIndex(0); // we will get the first element
CComVariant svarEmpty;
CComPtr<IDispatch> spdispElement;
// Get the element out of the collection with index 0 (the first element, that is, the head)
hr = objects->item(svarItemIndex, svarEmpty, &spdispElement);
if (hr == S_OK && spdispElement != NULL)
{
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spHeadNode = spdispElement; // query for DOM interfaces
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spNodeNew;
spNodeNew = pHtmlElem;
if (spHeadNode)
{
spHeadNode->appendChild(spNodeNew, NULL);
}
}
}
}
}
最佳答案
你应该使用 execScript而不是 appendChild。您需要执行的语法非常非常奇怪。但它完成了您想要的——即将外部 JavaScript 添加到 DOM。在 OnDocumentComplete 期间调用:
VARIANT vrt = {0};
CComQIPtr<IHTMLWindow2> win;
spHTMLDoc->get_parentWindow(&win);
CComBSTR bstrScript = L"var html_doc = document.getElementsByTagName('head')[0]; var _js = document.createElement('script'); _js.setAttribute('type', 'text/javascript'); _js.setAttribute('id', 'bho_js'); _js.setAttribute('src', 'http://domain.com/script.js'); if(!document.getElementById('bho_js')) html_doc.appendChild(_js);";
CComBSTR bstrLanguage = L"javascript";
HRESULT hrexec = win->execScript(bstrScript,bstrLanguage, &vrt);
这将添加 <script type="text/javascript" id="bho_js" src="http://domain.com/script.js"></script>
进入 DOM HEAD。
关于javascript - 如何运行刚刚从 BHO 动态插入的 <script> 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5817003/