I have a COM client executable which spawns a new IE process and grabs a reference to the IWebBrowser2 interface, and I would like to inject a JavaScript tag into the webpage that IE loads.
Currently this is what I am doing:
void Document::AddScript(const std::wstring script, const std::wstring id) {
HRESULT hr = S_OK;
IHTMLElement* pHtmlElem;
CComVariant vJavascript = "text/javascript";
CComBSTR vScriptContents = script.c_str();
CComBSTR vId = id.c_str();
hr = _pDocument2->createElement(_T("script"), &pHtmlElem);
if (SUCCEEDED(hr) && pHtmlElem != NULL)
{
hr = pHtmlElem->setAttribute(_T("type"), vJavascript);
hr = pHtmlElem->put_innerText(vScriptContents);
hr = pHtmlElem->put_id(vId);
}
CComPtr<IHTMLElement> body;
hr = pDocument->get_body(&body);
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spBodyNode = body;
CComQIPtr<IHTMLDOMNode, &IID_IHTMLDOMNode> spNodeNew;
hr = pHtmlElem->QueryInterface(&spNodeNew);
CComPtr<IHTMLDOMNode> node;
if (spBodyNode)
{
hr = spBodyNode->appendChild(spNodeNew, &node);
}
}
The HRESULT returned from spBodyNode->appendChild is coming back as S_OK; however, nothing is getting appended to the page. What can I do to get
<script id="myScript">
function xyz(){
//...
}
</script>
onto the page?
EDIT
The functions added by this method need to be executable in the web page.
Did some quick research on the topic, and found this article which shares a library using the IWebBrowser2 as a constructor's argument. I think it will suffice.
Also, you may try using a Browser Helper Object (seems more pratical even though does not uses that interface). Here: link
Good Luck