I have just discovered the window.external object that allows to call C# function in a winform program hosting a IE-like browser.

I red the doc on MSDN and some threads on stackOverflow but I didn't found if those calls are synchronous or not, and, is it customable ?

The only thing I have founded in the MSDN doc doesn't speak about this subject =/

有帮助吗?

解决方案

These calls are naturally synchronous, but often it makes sense to process them asynchronously, to avoid otherwise possible reentrancy into JavaScript code. You could use SynchronizationContext.Post for that.

E.g. you call window.external.TestMethod() from JavaScript. On the .NET side it may look like this:

this.webBrowser.ObjectForScripting = new ObjectForScripting(this.webBrowser);

// ...

[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public class ObjectForScripting
{
    WebBrowser _browser;
    SynchronizationContext _context = SynchronizationContext.Current;

    public ObjectForScripting(WebBrowser browser)
    {
        _browser = browser;
    }

    public void TestMethod()
    {
        _context.Post(_ =>
        {
            _browser.Document.InvokeScript("alert", new object[] { 
                "Process a call from JavaScript asynchronosuly." });
        }, null);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top