我能夠使它在IE10和IE11上工作。我使用appendChild方法並將HTMLScriptElement附加到它,而不是insertAdjacentHTML注入。以下是我的代碼的摘錄。
LOG(_T("Beginning script injection"));
CComPtr<IHTMLElement> htmlElement;
if (!SUCCEEDED(hr = doc->createElement(CComBSTR("script"), &htmlElement)))
{
LOG_ERROR(_T("createElement of type script failed"), hr);
return;
}
CComPtr<IHTMLScriptElement> htmlScript;
if (!SUCCEEDED(hr = htmlElement.QueryInterface<IHTMLScriptElement>(&htmlScript)))
{
LOG_ERROR(_T("QueryInterface<IHTMLScriptElement> failed"), hr);
return;
}
htmlScript->put_type(CComBSTR("text/javascript"));
htmlScript->put_text(CComBSTR(js.c_str()));
CComPtr<IHTMLDocument3> htmlDocument3;
if (!SUCCEEDED(hr = doc.QueryInterface<IHTMLDocument3>(&htmlDocument3)))
{
LOG_ERROR(_T("QueryInterface<IHTMLDocument3> failed"), hr);
return;
}
CComPtr<IHTMLElementCollection> htmlElementCollection;
if (!SUCCEEDED(hr = htmlDocument3->getElementsByTagName(CComBSTR("head"), &htmlElementCollection)))
{
LOG_ERROR(_T("getElementsByTagName failed"), hr);
return;
}
CComVariant varItemIndex(0);
CComVariant varEmpty;
CComPtr<IDispatch> dispatchHeadElement;
if (!SUCCEEDED(hr = htmlElementCollection->item(varEmpty, varItemIndex, &dispatchHeadElement)))
{
LOG_ERROR(_T("item failed"), hr);
return;
}
if (dispatchHeadElement == NULL)
{
LOG_ERROR(_T("dispatchHeadElement == NULL"), hr);
return;
}
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spHeadNode = dispatchHeadElement; // query for DOM interfaces
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spNodeNew = htmlScript;
if (spHeadNode)
{
if (!SUCCEEDED(hr = spHeadNode->appendChild(spNodeNew, NULL)))
{
LOG_ERROR(_T("dispatchHeadElement == NULL. Script injection failed"), hr);
return;
}
LOG(_T("Script injection SUCCESS!"));
}