Javascript中无法访问C#类属性

时间:2015-08-17 14:00:00

标签: javascript c# webview com win-universal-app

我想通过C#WebView-Control在JavaScript中访问我的类。 因此我使用WebView.AddWebAllowedObject方法。但是,如果我分配一个属性,它工作正常,但如果我指定整个类来获取js中的所有属性,所有属性(和方法btw)都是"未定义"。我尝试了在www中找到的所有内容。请参阅附带的代码:

        //The class I want to make accessible
        [AllowForWeb, ComVisible(true)]
        [MarshalingBehavior(MarshalingType.Agile)]
        public class DeviceInformation
        {
            public string IPAdress { get; private set; }

            public DeviceInformation()
            {
                IPAdress = GetIPAdress();
            }

            public string GetDeviceUUID()
            {
                EasClientDeviceInformation deviceinfo = new EasClientDeviceInformation();
                return deviceinfo.Id.ToString();
            }

            public string GetIPAdress()
            {
                List<string> ipAddresses = new List<string>();
                var hostnames = NetworkInformation.GetHostNames();
                foreach (var hn in hostnames)
                {
                    if (hn?.IPInformation != null && (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71 ||
                        hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
                    {
                        string ipadress = hn.DisplayName;
                        return ipadress;
                    }
                }
                return string.Empty;
            }
        }

此处对象已初始化。

DeviceInformation devinf = new DeviceInformation();
private void View_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        if (args.Uri.Host == "")
        {
            //win_ipadress has an ipadress as value
            view.AddWebAllowedObject("win_ipadress", devinf.IPAdress);
            //deviceInformation is initialized as well but I have no access to its attributes
            view.AddWebAllowedObject("deviceInformation", devinf);
        }
    }

这就是我在js中称呼它的方式:

else if ($.os.ie) {
                    myIpAdr = window.win_ipadress;
                    //Throws an exception because GetIPAdress() is "undefined"
                    myIpAdr = window.deviceInformation.GetIPAdress();
                }

我在Windows Universal App中使用它。 Javascript和WebView中显示的HTML-Code已经在Android和iOS中使用。

1 个答案:

答案 0 :(得分:3)

我认为您需要定义以小写字符开头的方法名称。

例如:将GetIPAddress更改为getIPAddress。

我在我身边进行了测试,发现如果我使用大写名称&#39; GetIPAddress&#39;,它就无法工作。但是如果我使用getIPAddress,它就可以工作。

在我阅读kangax在this帖子中的解释后,我认为这是有道理的。

<强> [更新]

由于在对方法名称进行更改后仍然无法正常工作,我认为该问题应该与您公开Windows运行时对象的方式有关。我猜你只是定义了DeviceInformation类,并尝试在同一个项目中使用它。

首先,我们需要创建一个单独的Windows通用Windows运行时组件项目。

应将c#类DeviceInformation放入此项目中。保持相同的代码。

然后,在您的通用应用程序项目中,添加对Windows运行时组件的引用,并保留其余代码以使用Windows运行时对象。

[更新2]

刚刚注意到VS中一个有趣的行为。无论我们在C#中定义的Method名称是以大写还是小写开头,visual studio intellisense都会显示小写,因此当我们尝试在js中使用它时,方法名称将自动转换。