質問

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