Search code examples
webassemblyvisual-studio-2022uno-platform

Uno Platform WASM URL routing


I'm trying to write a simple blog engine in Uno WASM. I'd need to retrive the URL string to process it and route the request to a page or a method, but cannot find any documentation on this topic. I'm using the last Uno template in Visual Studio 2022


Solution

  • It is possible to use LaunchActivatedEventArgs.Arguments property to retrieve the query string arguments in OnLaunched method of App.xaml.cs:

    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
       ...
       var arguments = e.Arguments;
       // Parse arguments and navigate somewhere based on them
    }
    

    Full route-based navigation you must first enable it by specifying the root route of your app (see docs). Essentially you need to add the base path to your WebAssembly .csproj:

    <PropertyGroup>
      <WasmShellWebAppBasePath>/</WasmShellWebAppBasePath>
    </PropertyGroup>
    

    Then you can get the actual URL on WASM using:

    #if __WASM__
    var href = Foundation.WebAssemblyRuntime.InvokeJS("window.location.href");
    // Parse the URL and navigate somewhere
    #endif
    

    The other way around - when you want to set the current URL, you can use window.history.pushState:

    Foundation.WebAssemblyRuntime.InvokeJS(
       "window.history.pushState(\"" + someUrl + "\",\"" + pageTitle + "\"");
    

    This can be done more easily using Uno.Extensions, which includes support for routing, documentation for this will be coming soon.