MSHTML : Calling member of javascript object?

≡放荡痞女 提交于 2019-12-08 13:02:09

问题


Using the .NET WebBrowser control, it is fairly simple to execute a member of an HtmlElement.

Assuming there is a JavaScript object called "player" with a member called "getLastSongPlayed"; calling this from the .NET WebBrowser control would go something like this:

HtmlElement elem = webBrowser1.Document.getElementById("player");
elem.InvokeMember("getLastSongPlayed");

Now my question is: How do I accomplish that using mshtml ?

Thanks in advance, Aldin

EDIT:

I got it up and running, see my answer below !


回答1:


FINALLY !! I got it up and running !

The reason for the

System.InvalidCastException

that was thrown, whenever I tried to reference the parentWindow of an mshtml.IHTMLDocument2 and / or assign it to an mshtml.IHTMLWindow2 window object had to do with Threading.

For some, unknown to me, reason it seems that the COM objects of mshtml.IHTMLWindow are operating on another Thread that must be of Single-Threaded Apartment (STA) state.

So the trick was, calling / executing the required piece of code on another Thread with STA state.

Here's a sample code:

SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer

bool _isRunning = false;

private void IE_DocumentComplete(object pDisp, ref obj URL)
{
    //Prevent multiple Thread creations because the DocumentComplete event fires for each frame in an HTML-Document
    if (_isRunning) { return; }

    _isRunning = true;

    Thread t = new Thread(new ThreadStart(Do))
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}

private void Do()
{
    mshtml.IHTMLDocument3 doc = this.IE.Document;

    mshtml.IHTMLElement player = doc.getElementById("player");

    if (player != null)
    {
        //Now we're able to call the objects properties, function (members)
        object value = player.GetType().InvokeMember("getLastSongPlayed", System.Reflection.BindingFlags.InvokeMethod, null, player, null);

        //Do something with the returned value in the "value" object above.
    }
}

We're now also able to reference the parentWindow of an mshtml.IHTMLDocument2 object and execute a sites script and / or our own (remember it must be on an STA thread):

mshtml.IHTMLWindow2 window = doc.parentWindow;

window.execScript("AScriptFunctionOrOurOwnScriptCode();", "javascript");

This might save someone from headaches in the future. lol



来源:https://stackoverflow.com/questions/9277839/mshtml-calling-member-of-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!