How to call the C # method in javascript using GeckoFX as the envelope of XULRunner


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?

Just like below:

C# part:

private GeckoWebBrowser weBrowser;
    public browser()
        weBrowser = new GeckoWebBrowser();
        weBrowser.Parent = this;
        weBrowser.Dock = DockStyle.Fill;

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

javascript part:

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

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

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:

public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
    string payload = null;

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

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

    Assert.AreEqual("some data", payload);

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.

Hope that helps.