如何通过使用GeckoFX作为XULRunner的包装调用C#方法在JavaScript [英] How to call C# method in javascript by using GeckoFX as the wrapper of XULRunner

查看:2894
本文介绍了如何通过使用GeckoFX作为XULRunner的包装调用C#方法在JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的 GeckoFX16 XULRunner的-16.0.2.en-US.win32 在我的项目。
的事情是,我想打电话给在JavaScript中的C#方法。

I am using GeckoFX16 and xulrunner-16.0.2.en-US.win32 in my project. The thing is, I want to call a C# method in javascript.

我很好奇,是有办法做到这一点?

I am curious, is there a way to do this?

C#部分:

就像下面b
$ b

C# part:

private GeckoWebBrowser weBrowser;
    public browser()
    {
        InitializeComponent();
        Gecko.Xpcom.Initialize("xulrunner");
        weBrowser = new GeckoWebBrowser();
        weBrowser.Parent = this;
        weBrowser.Dock = DockStyle.Fill;
        weBrowser.Navigate("test.html");
    }

    public string loadData(){
        //load data from local file.
        return str;
    }



的JavaScript 部分:

<script type='text/javascript'>
    var data = window.loadData();
    alert(data);
</script>



我在这个领域新的,我会是否有可能欣赏!

I am new in this area, I’ll appreciate if it is possible!

推荐答案

您可以使用的 MessageEvent的来调用C#代码,但据我知道你不能再返回一个字符串像你想。其中一个单元测试演示了如何调用C#代码:

You can use a MessageEvent to invoke code in c#, but as far as I know you can't then return a string like you're wanting to. One of the unit tests demonstrates how to invoke the c# code:

[Test]
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
    string payload = null;

    browser.AddMessageEventListener("callMe", ((string p) => payload = p));

    browser.LoadHtml(
        @"<!DOCTYPE html>
                     <html><head>
                     <script type='text/javascript'>
                        window.onload= function() {
                            event = document.createEvent('MessageEvent');
                            var origin = window.location.protocol + '//' + window.location.host;
                            event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
                            document.dispatchEvent (event);
                        }
                    </script>
                    </head><body></body></html>");

    browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
    Assert.AreEqual("some data", payload);
}



我知道这很尴尬,但你可以使用C# - > JavaScript的调用获取数据返回到JavaScript的土地。见的此问题了解如何做到这一点。所以,你的JavaScript将首先发出这条消息到C#的土地,那么它会得到你所需要的字符串值的回调。

I know it's awkward, but you could then use a c#-->javascript call to get data back to javascript-land. See This Question for how to do that. So your javascript would first send this message to c# land, then it would get a callback with the string value you need.

希望有所帮助。

这篇关于如何通过使用GeckoFX作为XULRunner的包装调用C#方法在JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆