dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.26k stars 1.76k forks source link

Request to add Proxy URLs feature to HybridWebView #25867

Open itsazoo opened 1 week ago

itsazoo commented 1 week ago

Description

A core component I've been using to migrate to MAUI is the Proxy URLs API from Eilon/MauiHybridWebView. This feature smoothly replaces our old communication bridge between Javascript and C#. It would be amazing to have this in the MAUI 9 version of HybridWebView.

The HybridWebView control can redirect URL requests to native code, and allow custom responses streams to be set. This allows scenarios such as dynamically generating content, loading content from compressed files like ZIP or SQLite, or loading content from the internet that doesn't support CORS. Eilon/MauiHybridWebView

Public API Changes

The C# side has an event handler to process proxy requests coming from Javascript. The request content is packaged in HybridWebViewProxyEventArgs with the following properties: Property Type Description
QueryParams IDictionary<string, string> The query string parameters of the request. Note that all values will be strings.
ResponseContentType string The content type of the response body. Default: "text/plain"
ResponseStream Stream The stream to use as the response body.
Url string The full URL that was requested.
myWebView.ProxyRequestReceived += async ((HybridWebViewProxyEventArgs)args) =>
{
    //Use the query string parameters to determine what to do.
    if (args.QueryParams.TryGetValue("myParameter", out var myParameter))
    {
        //Add your logic to determine what to do. 
        if (myParameter == "myValue")
        {
            //Add logic to get your content (e.g. from a database, or generate it).
            //Can be anything that can be turned into a stream.

            //Set the response stream and optionally the content type.
            args.ResponseStream = new MemoryStream(Encoding.UTF8.GetBytes("This is the file content"));
            args.ResponseContentType = "text/plain";
        }
    }
};

Javascript can send data to C# over the proxy url.

var request = window.location.origin + '/proxy?myParameter=' + encodeURIComponent('myValue') + '&secondParameter=foo' ;

fetch(request)
    .then(response => response.text())
    .then(data => console.log(data));

Intended Use-Case

Our .NET app's legacy code communicates between a C# backend and JavaScript frontend over an SSL stream. The Proxy URLs feature in HybridWebView offers a streamlined API that reduces much of this legacy code and preserves core functionality with minimal changes, making it a close fit for our current setup.

I really look forward to seeing this feature in MAUI's HybridWebView. Thank you for considering this request!