I just started using Visual Studio 2010 C# IDE today.
I'm trying to inject javascript to WebBrowser component and followed the answer from stackoverflow:
How to inject Javascript in WebBrowser control?
HtmlElement txtBox = webBrowser1.Document.GetElementById("UserEmailShortcut"); //js HtmlElement scriptOne = webBrowser1.Document.CreateElement("script"); IHTMLScriptElement element = (IHTMLScriptElement)scriptOne.DomElement; element.text = "function sayHello() { alert('hello') }"; txtBox.AppendChild(scriptOne); webBrowser1.Document.InvokeScript("sayHello");
Now there is red wavy line under IHTMLScriptElement saying:
Error 1 The type or namespace name 'IHTMLScriptElement' could not be found (are you missing a using directive or an assembly reference?) C:\Users\m-tak\documents\visual studio 2010\Projects\winformWithWebBrowserTest\winformWithWebBrowserTest\Form1.cs 25 13 winformWithWebBrowserTest
I've looked documentation http://msdn.microsoft.com/en-us/library/aa768904(v=VS.85).aspx
but I can't figure why. Isn't this already included and just need to include like "using IHTMLScriptElement
" (which didn't work..)
Project + Add Reference, select Microsoft.mshtml. If it doesn't appear in the list (it is a PIA) then use the Browse tab and select c:\windows\system32\mshtml.tlb
Add a using directive at the top of the source code file:
using mshtml;
Beware that you have a deployment detail. If the PIA isn't installed on the target machine, which is not unlikely, then the best thing to do is to set the Copy Local property of the assembly reference to True. That creates the Microsoft.mshtml.dll file in the build folder. Copy it, along with your EXE onto the target machine. There are a few cases where a PIA is required, not this one.
Update to this old post, .NET 4+ and VS2010+ now support the "Embed Interop Types" reference assembly property. Also known as the "No PIA" feature. This obsoletes the need for PIAs and is the superior way to deal with interop assemblies. It is set to True automatically, unless your project got started on an old version of VS.
It has no down-sides, you no longer have to deploy the interop assembly and the interop types you use are now embedded in your executable file. Just the ones you use. A small change might be required in your code, if you now create the COM object with new XxxxClass()
then you need to remove the "Class" part of the name.
IHTMLScriptElement is defined in the Mshtml. You need to add a reference to the the Microsoft HTML Object Library and then add a "using mshtml" for VS to resolve IHTMLScriptElement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With