简体   繁体   English

如何从 c# 接收 JavaScript 中的变量?

[英]How to receive a variable in JavaScript from c#?

So I'm trying to open up an HTML file through a WPF UI(XAML) hyperlink and pass some coordinates to the HTML file, which uses JavaScript to create a map that centers around, hopefully, the coordinates I'm trying to pass.所以我试图通过 WPF UI(XAML) 超链接打开一个 HTML 文件,并将一些坐标传递给 HTML 文件,该文件使用 JavaScript 创建一个以我试图传递的坐标为中心的地图。 coord1 and coord2 are doubles. coord1 和 coord2 是双精度的。

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        String coords = coord1 + " " + coord2;
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri, coords));
        e.Handled = true;
    }

This is the JavaScript end where I'm trying to receive the variable coords :这是我试图接收变量coords的 JavaScript 端:

<script type='text/javascript'>
    var map;
    var coords = '<%=coords%>';

   function GetMap() {

    map = new Microsoft.Maps.Map('#myMap', {center: new Microsoft.Maps.Location(55, 0)});
    ...

I got '<%=coords%>' from online but it literally just returns <%=coords> .我从网上得到了'<%=coords%>'但它实际上只是返回了<%=coords> I'm trying to take the two coordinate points to replace the 55 and 0.我试图取两个坐标点来代替 55 和 0。

I didn't post the XAML code, but the C# code opens up the HTML file when a hyperlink is clicked and I believe the string "coords" is being passed with the data, but I just don't know how to receive it.我没有发布 XAML 代码,但 C# 代码在单击超链接时打开了 HTML 文件,我相信字符串“coords”正在与数据一起传递,但我只是不知道如何接收它。

There are two ways to pass data into a HTML web page from a WPF app, assuming you control the source code of the web page.假设您控制网页的源代码,有两种方法可以将数据从 WPF 应用程序传递到 HTML 网页。 Note that <%=coords%> is an ASP.NET thing that passes information from the code behind to the front end on load and would require a lot more work to get working (there are easier options).请注意, <%=coords%>是一个 ASP.NET 的东西,它在加载时将信息从后面的代码传递到前端,并且需要更多的工作才能开始工作(有更简单的选项)。

Method 1方法一

If you only want one way communication (pass into the web page, but don't need to send anything back to WPF C#), you can pass the information in as a query string, then parse that when your application loads.如果您只想要一种方式的通信(传递到网页,但不需要将任何内容发送回 WPF C#),您可以将信息作为查询字符串传递,然后在应用程序加载时对其进行解析。 This is really easy.这真的很容易。 Here is an example of a web page that takes in a URL with optional center and zoom parameters the look like this test.html?center=51.50632,-0.12714&zoom=15这是一个网页示例,它接收带有可选centerzoom参数的 URL,如下所示test.html?center=51.50632,-0.12714&zoom=15

<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>

    <meta charset="utf-8" />
    <meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
</head>
<body>

    <div id='myMap' style='width: 100vw; height: 100vh;'></div>

<script>
    var map;
    
    function GetMap(){  
        //Default center/zoom values.
        let center = new Microsoft.Maps.Location(0, 0);
        let zoom = 1;

        //Get the queryStringuery string of the URL. 
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        
        //Extract center infromation from query string. 
        if (urlParams.has('center')) {
            //Parse coordinates from the center parameter. Assume that string is in the format "latitude, longitude". Comma/space optional, must have atleast one. 
            let parts = urlParams.get('center').split(/[,\s]+/gi);
            
            if(parts.length >= 2){
                let lat = parseFloat(parts[0]);
                let lon = parseFloat(parts[1]);
                
                if(!isNaN(lat) && !isNaN(lat)){
                    center = new Microsoft.Maps.Location(lat, lon);
                }
            }
        } 
        
        if (urlParams.has('zoom')) {
            let z = parseInt(urlParams.get('zoom'));
            
            if(!isNaN(z)){
                zoom = z;
            }   
        }
        
         map = new Microsoft.Maps.Map('#myMap', {
            center: center,
            zoom: zoom
         });
    }
</script>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=[Your Bing Maps Key]' async defer></script>
</body>
</html>

The main limitations of this approach are:这种方法的主要限制是:

  • You can only pass as much information as the max URL length will allow (2083 characters).您只能传递最大 URL 长度允许的信息(2083 个字符)。
  • Information is only sent once, when the page loads.信息仅在页面加载时发送一次。 If you want to send new information, then the page has to be reloaded (inefficient, and can generate additional map sessions when using Bing Maps).如果要发送新信息,则必须重新加载页面(效率低下,并且在使用 Bing 地图时会生成额外的地图会话)。
  • No way to send information back to the WPF app.无法将信息发送回 WPF 应用程序。

Method 2方法二

If you want to two-way communication, or want to avoid the limitations of method 1 you can wrap a web browser control in your application and make use of interoperability.如果您想要双向通信,或者想要避免方法 1 的限制,您可以在您的应用程序中包装一个 Web 浏览器控件并利用互操作性。 Currently WPF provides WebView2 which allows you to embed the Edge browser into your application https://docs.microsoft.com/en-us/microsoft-edge/webview2/get-started/wpf Here is a great detailed blog post on how to do this: https://weblog.west-wind.com/posts/2021/Jan/26/Chromium-WebView2-Control-and-NET-to-JavaScript-Interop-Part-2目前 WPF 提供 WebView2,它允许您将 Edge 浏览器嵌入到您的应用程序中https://docs.microsoft.com/en-us/microsoft-edge/webview2/get-started/wpf这是一篇非常详细的博客文章,介绍如何这样做: https ://weblog.west-wind.com/posts/2021/Jan/26/Chromium-WebView2-Control-and-NET-to-JavaScript-Interop-Part-2

Alternatively, you can also use Chromium/CefSharp ( https://cefsharp.github.io/ ) rather than WPF's WebView2 control (it likely will make your application a lot larger since it won't leverage the browser that's already installed on the system: https://dev.to/noseratio/comparing-process-working-sets-of-webview-based-windows-desktop-apps-5dkk ).或者,您也可以使用 Chromium/CefSharp ( https://cefsharp.github.io/ ) 而不是 WPF 的 WebView2 控件(它可能会使您的应用程序更大,因为它不会利用系统上已安装的浏览器: https ://dev.to/noseratio/comparing-process-working-sets-of-webview-based-windows-desktop-apps-5dkk)。

Update: Method 3更新:方法 3

You can read your HTML file as a string and do a find and replace on your placeholder.您可以将 HTML 文件作为字符串读取,并在占位符上进行查找和替换。 In the below example I've made the HTML file an embedded resource (likely what you will need to do if you want to ship this to others at some point).在下面的示例中,我将 HTML 文件设置为嵌入式资源(如果您想在某个时候将其发送给其他人,您可能需要这样做)。 I called it mapPage.html and have it in the root directory of the project.我将其命名为mapPage.html并将其放在项目的根目录中。 Add the html file to your project, go to properties and set build action to embedded resource.将 html 文件添加到您的项目中,转到属性并将构建操作设置为嵌入式资源。 To read it you will need to include the namespace of your project in the file name path, in my case the namespace is SimpleWebBrowser , thus the file name would when reading would be SimpleWebBrowser.mapPage.html .要阅读它,您需要在文件名路径中包含项目的命名空间,在我的情况下,命名空间是SimpleWebBrowser ,因此读取时文件名将是SimpleWebBrowser.mapPage.html Then in your C# code you could have a method like this:然后在您的 C# 代码中,您可以使用如下方法:

private void LoadMap(double latitude, double longitude)
{
    Assembly assembly = Assembly.GetExecutingAssembly();
    using (var reader = new StreamReader(assembly.GetManifestResourceStream("SimpleWebBrowser.mapPage.html")))
    {
        var html = reader.ReadToEnd();
        html = html.Replace("<%=coords%>", latitude + " " + longitude);

        myBrowser.NavigateToString(html);
    }
}

You HTML code would then handle the input like this:然后,您的 HTML 代码将像这样处理输入:

<script type='text/javascript'>
    var map;
    var coords = '<%=coords%>';

    function GetMap() {
        //Default center.
        var center = new Microsoft.Maps.Location(55, 0);
       
        //Parse the coords string and get lat/lon values.
        var parts = coords.split(' ');
       
        if(parts.length >= 2){
            let lat = parseFloat(parts[0]);
            let lon = parseFloat(parts[1]);

            if(!isNaN(lat) && !isNaN(lat)){
                center = new Microsoft.Maps.Location(lat, lon);
            }
        }
     
        map = new Microsoft.Maps.Map('#myMap', {center: });
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM