Partager via


Interop with Internet Explorer

I find that one of the best ways to learn something new is to not fire up a search engine and start reading what other people have done but to do it yourself. Someone asked me yesterday how you would go about calling a .NET assembly from client side JScript in Internet Explorer (handy if you're using HTML based UI's). Now I've done plenty of COM calls from JScript using C++ and converting that to C# is easy as long as you follow a few simple steps. Here are those steps (with a link to the project)

1. Create your assembly (I use a .NET class library) keeping COM Interop best practices in mind. This includes:

  • Avoid using parameterized constructors.
  • Avoid using static methods.
  • Define event-source interfaces in managed code.
  • Include HRESULTs in user-defined exceptions.
  • Supply Globally Unique Identifiers (GUIDs) for types that require them (using the GUID attribute)
  • Expect inheritance differences.

2. Create a post build event to call regasm.exe passing the assembly name as the command line argument (see sample project).

3. Create an HTML page that creates the .NET type similar to the following:

function CallOutToCSharpAssembly()
{
var myAssembly = new ActiveXObject( "IEToCSharp.IEInterop" );
alert( asm.HelloWorld );
}

Note that the progid for your assembly is of the form namespace.classname. You can change this by applying the ProgId attribute to your type.

4. Build your .NET assembly and open your HTML page in IE. You should receive ActiveX warnings since your COM object is not marked safe for scripting. In cases like this, I now punt to the search engines.

Click here to download the sample project.

So, this is overly simplistic but should be a good starting point to anyone wanting to interop with IE without resorting to unmanaged C++ code.

Comments