在脱机WebBrowser控件中运行异步Javascript

时间:2018-08-29 10:36:27

标签: c# .net webbrowser-control

我正在尝试从WebBrowser控件中运行的javascript的诺言中获取数据

    [TestMethod]
    public void RunJS()
    {
        var thread = new Thread(() =>
        {
            var browser = new WebBrowser();

            var objectForScripting = new ObjectForScripting();
            browser.ObjectForScripting = objectForScripting;

            browser.Navigate("about:blank");
            var doc = browser.Document.OpenNew(true);
            doc.Write(@"
            <!doctype html>
            <html>
                <head>
                    <meta http-equiv='X-UA-Compatible' value='IE=Edge'/>
                    <script >
                         <!-- *snip* promise polyfill code pasted in from https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.min.js --> 
                    </script>
                    <script>
                        function getPages() {

                            window.Promise.resolve([
                                        'page 1',
                                        'page 2'
                                    ])

                            .then(function(a) {
                                window.external.send(a);                          
                            });


                        }
                        getPages();
                    </script>
                </head>
                <body>

                </body>
            </html>

        ");

        });
        thread.SetApartmentState(ApartmentState.STA);
        thread.DisableComObjectEagerCleanup(); // i just tried this to see if it made a difference
        thread.Start();
        Thread.Sleep(10000); // add this because I thought sleeping on the main thread might help
        thread.Join();
    }

最终的目的是调用异步API,但在这里我只是添加了一个简单的Promise来使其工作。问题是then()从未被调用。我怀疑这与线程(和setTimeout)有关,但我不知道该如何解决。

ObjectForScripting类仅具有一种收集数据的方法

[ComVisible(true)] 
public class ObjectForScripting 
{
    public object args;
    public void send(object args)
    {
        this.args = args;
    } 
}

我在send方法中设置了一个断点,但是从未调用过它。

如果我仅将以下内容用作javascript

function getPages() {
    window.external.send(a);                                     
}
getPages();

断点被击中

0 个答案:

没有答案