我提到的方法可以从WinForm App调用WebBrowser控件的AngularJS函数

时间:2017-02-06 10:51:39

标签: angularjs html5 winforms typescript webbrowser-control

我的要求是在WinForm应用程序的Web浏览器控件中加载HTML5 / AngularJS表单,并在两者之间交换数据。

要将.Net表单中的数据传递给WebBrowser控件HTML / Angular表单,我想调用HTML页面的简单JavaScript方法,该方法随后将触发Angular复杂工作流程。

这就是我从winform调用JavaScript函数的方法。

WebBrowserControl1.InvokeScript("FunctionName", new object[] {"param"});

您能否建议这种方法是否适用于大型应用程序,或者是否有更好的方法将数据从.net winform传递到webbrowser AngularJS表单。

请注意,不久之后我发布了一个问题来调用Typescript函数,我也得到了答案。然而,这是从webbrowser控件初始化Angular类,这对于复杂的Angular应用程序是不可行的。

因此我认为这种方法可以调用Angular页面的简单JS函数,并且会触发复杂的角度流。

Call TypeScript function from C# webbrowser control

提前感谢您的帮助。

谢谢, Manoj

1 个答案:

答案 0 :(得分:1)

这将让你进行单向沟通,这完全没问题。对于双向通信,您应该查看ObjectForScripting

有了这个,你可以让你的JavaScript直接调用C#方法通过window.external

发回数据

这是来自MSDN的明显粘贴。

    webBrowser1.AllowWebBrowserDrop = false;
    webBrowser1.IsWebBrowserContextMenuEnabled = false;
    webBrowser1.WebBrowserShortcutsEnabled = false;
    webBrowser1.ObjectForScripting = this;
    // Uncomment the following line when you are finished debugging.
    //webBrowser1.ScriptErrorsSuppressed = true;

    webBrowser1.DocumentText =
        "<html><head><script>" +
        "function test(message) { alert(message); }" +
        "</script></head><body><button " +
        "onclick=\"window.external.Test('called from script code')\">" +
        "call client code from script code</button>" +
        "</body></html>";

编辑:更新答案以显示在网页上运行脚本的其他方式。

        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
            {
                WebBrowser wb = sender as WebBrowser;

                HtmlElement he = webBrowser1.Document.CreateElement("script");
                he.InnerHtml = "alert('popup');";
                wb.Document.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterEnd, he);

            }    

另外,请注意内存泄漏。 Web浏览器控件具有与Internet Explorer相同的呈现和JavaScript引擎,但与IE不同,当它泄漏内存时,它无法重新启动选项卡进程。它存在于您的流程空间中。我说要小心,因为Angular JS和IE在历史上并没有很好地融合在一起。确保正确处理您的范围等。