Passing javascript Date object to C# WebBrowser control using window.external

自闭症网瘾萝莉.ら 提交于 2019-12-11 04:26:05

问题


I am able to call C# methods of WebBrowser.ObjectForScripting with javascript window.external from WebBrowser WinForms control and pass string, int, bool etc. However I don't know how to pass javascript Date object and somehow convert/marshal it to .NET DateTime class.

Obviously, I could pass a string and parse it, but this is really not the point. I'm just curious how could I do it with javascript Date and .NET DateTime?


回答1:


You can take advantage of the fact that dates in Javascript are expressed as the number of milliseconds elapsed since the UNIX epoch (1970-01-01 00:00:00 UTC). Use the valueOf() method to obtain that value from a Date object :

var millisecondsSinceEpoch = yourDate.valueOf();

If you can marshal that value to C# as a double, you can create the appropriate DateTime object using its constructor and the AddMilliseconds() method:

DateTime yourDateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(millisecondsSinceEpoch);



回答2:


I found better solution for my project.

in javascript:

var date = new Date();
myComObject.DoSomething(date.getVarDate());

in C#

[ComVisible(true)]
public class Foo
{
    public void Bar(DateTime dateTime)
    {
        Console.WriteLine(dateTime);
    }
}



回答3:


I finally got it working. I don't know why, but I am unable to use it with dynamic. Here is the solution:

[ComVisible(true)]
public class Foo
{
    public void Bar(object o)
    {
        var dateTime = (DateTime)o.GetType().InvokeMember("getVarDate", BindingFlags.InvokeMethod, null, o, null);
        Console.WriteLine(dateTime);
    }
}


来源:https://stackoverflow.com/questions/5662128/passing-javascript-date-object-to-c-sharp-webbrowser-control-using-window-extern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!