简体   繁体   中英

Manipulate C# / UWP from HTML / JS

I just managed to implement a small webserver on my Raspberry Pi. The webserver is created as an UWP headless app.

It can use Javascript. Which is pretty helpful. I only just start with HTML and JS so I'm a big noob in this and need some help.

I already managed to show the same data I show on the webpage in a headed app on the same device.

Now I want to be able to manipulate the data from the webpage. But I don't know how I'm supposed to do that. I parse the HTML / JS as a complete string so I can't use variables I defined in code. I would need another way to do this.

My code for the webserver is currently this:

 public sealed class StartupTask : IBackgroundTask
{
    private static BackgroundTaskDeferral _deferral = null;        

    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        _deferral = taskInstance.GetDeferral();

        var webServer = new MyWebServer();

        await ThreadPool.RunAsync(workItem => { webServer.Start(); });
    }
}

class MyWebServer
{
    private const uint BufferSize = 8192;

    public async void Start()
    {
        var listener = new StreamSocketListener();

        await listener.BindServiceNameAsync("8081");

        listener.ConnectionReceived += async (sender, args) =>
        {
            var request = new StringBuilder();

            using (var input = args.Socket.InputStream)
            {
                var data = new byte[BufferSize];
                IBuffer buffer = data.AsBuffer();
                var dataRead = BufferSize;

                while (dataRead == BufferSize)
                {
                    await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial);
                    request.Append(Encoding.UTF8.GetString(data, 0, data.Length));
                    dataRead = buffer.Length;
                }
            }

            string query = GetQuery(request);

            using (var output = args.Socket.OutputStream)
            {
                using (var response = output.AsStreamForWrite())
                {
                    string htmlContent = "<html>";
                    htmlContent += "<head>";
                    htmlContent += "<script>";
                    htmlContent += "function myFunction() {document.getElementById('demo').innerHTML = 'Paragraph changed.'}";
                    htmlContent += "</script>";
                    htmlContent += "<body>";
                    htmlContent += "<h2>JavaScript in Head</h2>";
                    htmlContent += "<p id='demo'>A paragraph.</p>";
                    htmlContent += "<button type='button' onclick='myFunction()'>Try it!</button>";
                    htmlContent += "</body>";
                    htmlContent += "</html>";

                    var html = Encoding.UTF8.GetBytes(htmlContent);

                    using (var bodyStream = new MemoryStream(html))
                    {
                        var header =
                            $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";

                        var headerArray = Encoding.UTF8.GetBytes(header);
                        await response.WriteAsync(headerArray, 0, headerArray.Length);
                        await bodyStream.CopyToAsync(response);
                        await response.FlushAsync();
                    }
                }
            }
        };
    }

    public static string GetQuery(StringBuilder request)
    {
        var requestLines = request.ToString().Split(' ');

        var url = requestLines.Length > 1
            ? requestLines[1]
            : string.Empty;

        var uri = new Uri("http://localhost" + url);
        var query = uri.Query;
        return query;
    }
}

Your question is a bit vague, so I have to guess what you're trying to do. Do you mean that a browser (or another app with a Web view) will connect to your Pi server, grab some data off it, and then manipulate the data to format them / display them in a particular way on the page? If so, then first you need to decide how you get the data. You seem to imply the data will just be a stream of HTML, though it's not clear how you'll be passing that string to the browser. Traditional ways of grabbing the data might be with Ajax and possibly JSON, but it's also possible to use an old-fashioned iframe (maybe a hidden one) -- though if starting from scratch, Ajax would be better.

The basic issue is to know: what page will access the data on the server and in what format? Is it a local page served locally from the client app's filestore, that will then launch a connection to the server, grab the data and display them in a <div> or and <iframe> , or is it a page on your server that comes with the data incorporated in one part of the DOM, and you want to transform them and display them in another element?

Let's now assume your client app has received the data in an element like <div id="myData">data</div> . A script on the client page can grab those data as a string with document.getElementById('myData').innerHTML (see getElementById ). You can then transform the data as necessary with JavaScript methods. Then there are various DOM techniques for inserting the transformed data either back in the same element or a different one.

Instead, let's assume you have received the data via XMLHttpRequest . Then you'll need to identify just the data you want from the received object (that might involve turning the object into a string and using a regular expression, or more likely, use DOM selection methods on the object till you have the part of the data you want). When you've extracted the data / node / element, you can insert it into a <div> on your page as above.

Sorry if this is all a bit vague and abstract, but hopefully it can point you in the right direction to look up further things as needed. https://www.w3schools.com/ is a great resource for beginners.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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