Microsoft Edge Developer Documentation

repository·master·Indexed 42 days ago

https://github.com/microsoftedge/microsoftedge-documentation

Developer resources for building with the Microsoft Edge browser, featuring code snippets for Progressive Web Apps (PWAs) on Windows. Includes guides on integrating Windows Runtime (WinRT) APIs for native features such as StartupTask for automatic app launching, PopupMenu for custom context menus, Cortana voice commands via VCD files, and native inking support on canvas elements.

Tokens
8.9K
Snippets
16
Records
27
Agent score
53%

What's inside Microsoft Edge

  1. Overview of PWA task snippets for Windows

    master

    This repository provides ready-to-use code snippets for Progressive Web Apps (PWAs) running on Windows. These snippets allow developers to call Windows Runtime (WinRT) APIs to implement native app features and integrate web application UX with the Windows 10 operating system.

    Key capabilities covered include:

    • Tiles and notifications: Pinning app tiles, badge updates, and toast notifications via the Push API.
    • OS integration: File handler registration, app launch at startup, activation handling, and native messaging.
    • Windows UX customizations: Customizing app title bar colors, context menus, and desktop jump list commands.
    • Other tasks: Background tasks, caching, Cortana voice commands, WebView hosting, custom WinRT components, and Web authentication broker usage.
  2. Handle context menus in PWAs on Windows

    master

    The behavior of the contextmenu (right-click) event depends on how your Progressive Web App (PWA) is running:

    1. In the browser: The browser handles the contextmenu event with its default behavior, showing the standard Microsoft Edge context menu.
    2. As an installed Windows app (Standalone window): By default, no context menu is displayed in response to the contextmenu event.

    To provide a custom context menu when running as an installed Windows app, you can use the WinRT PopupMenu class via JavaScript.

  3. How to host a WebView control in a Windows 10 app

    master

    The EdgeHTML WebView control allows you to embed web content directly into a Universal Windows Platform (UWP) app or a PWA running on Windows 10. It functions similarly to an HTML iframe but provides advanced capabilities:

    • Advanced Loading: Supports remote HTTP pages, local app package pages (ms-appx-web:///*), ApplicationData folders (ms-appdata:///*), and in-memory streams (ms-local-stream:///*).
    • Browser Controls: Provides programmatic access to navigation history (goBack, goForward), stop, and refresh.
    • Interoperability: Allows JavaScript in the WebView to raise custom events to the app via MSWebViewScriptNotify, and allows the app to execute JavaScript in the WebView via invokeScriptAsync.
    • Content Capture: Supports capturing screenshots of web content for use with the Windows 10 app Share contract.
    • Lifecycle Events: Provides fine-grained events for navigation and content loading states.
  4. Getting started with PWAs on Windows

    master

    Before using these snippets, ensure you have a foundational understanding of PWA development and Windows integration:

    1. Learn PWA basics: Understand how to use service workers for offline support and push notifications via the Get started with Progressive Web Apps guide.
    2. Tailor for Windows: Learn how to run/debug your PWA as a Universal Windows Platform (UWP) app and how to use Windows Runtime (WinRT) APIs via the Tailor your PWA for Windows guide.
    3. Distribution: Learn how to submit your PWA to the Microsoft Store using the PWAs in the Microsoft Store guide.
  5. Build a custom context menu using the WinRT PopupMenu class

    master

    When your PWA runs as an installed Windows app, you can use the Windows.UI.Popups.PopupMenu API to create a native-feeling context menu.

    Implementation Steps:

    1. Feature Detection: Check for WinRT support using if (window.Windows && window.Windows.UI.Popups).
    2. Event Listener: Listen for the contextmenu event on the document.
    3. Coordinate Conversion: Because WinRT expects coordinates relative to the window, you must convert page coordinates (e.pageX, e.pageY) to WinRT coordinates. Use document.documentElement.msContentZoomFactor to account for zoom levels.
    4. Menu Construction: Use menu.commands.append() to add Windows.UI.Popups.UICommand objects (with unique IDs) or Windows.UI.Popups.UICommandSeparator objects.
    5. Display: Call menu.showAsync(coordinates) and handle the returned promise to determine which command was invoked via its id.
    // Check if WinRT is supported on the device
    if (window.Windows && window.Windows.UI.Popups) {
        document.addEventListener('contextmenu', function (e) {
            var menu = new Windows.UI.Popups.PopupMenu();
            menu.commands.append(new Windows.UI.Popups.UICommand("Option 1", null, 1));
            menu.commands.append(new Windows.UI.Popups.UICommandSeparator);
            menu.commands.append(new Windows.UI.Popups.UICommand("Option 2", null, 2));
    
            // Convert from page to WinRT coordinates
            function pageToWinRT(pageX, pageY) {
                var zoomFactor = document.documentElement.msContentZoomFactor;
                return {
                    x: (pageX - window.pageXOffset) * zoomFactor,
                    y: (pageY - window.pageYOffset) * zoomFactor
                };
            }
    
            menu.showAsync(pageToWinRT(e.pageX, e.pageY)).done(function (invokedCommand) {
                if (invokedCommand !== null) {
                    switch (invokedCommand.id) {
                        case 1: 
                            console.log('Option 1 selected');
                            break;
                        case 2: 
                            console.log('Option 2 selected');
                            break;
                        default:
                            break;
                    }
                } else {
                    console.log("Context menu dismissed");
                }
            });
        }, false);
    }
  6. Respond to jump list commands

    master

    When a user selects a jump list command, Windows activates your app and passes the item's arguments via the WebUIApplication.activated event.

    To differentiate a jump list command from a standard app launch, check the activatedEventArgs.arguments against the string you provided when creating the JumpListItem. Jump list commands trigger an activation of type Windows.ApplicationModel.Activation.ActivationKind.launch.

    Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
        if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.launch &&
            activatedEventArgs.arguments == "jump list command args") {
            // Respond to jumplist command specified by argument(s)
        }
    });
  7. Pin secondary tiles to the Start menu

    master

    Secondary tiles allow for deep linking to specific content within your PWA. Unlike primary tiles (which are created from the .appxmanifest and are unpinned by default), secondary tiles can be pinned programmatically by prompting the user for permission.

    To pin a secondary tile, use the WinRT SecondaryTile constructor and call the requestCreateAsync() method.

    Required Properties:

    • tileId: A unique string used to identify the tile for future updates or deletion.
    • displayName: The name shown on the tile and in its tooltip.
    • arguments: A string passed to the app via launchActivatedEventArgs.arguments to control behavior when the tile is launched.
    • visualElements.square150x150Logo: A URI (using the ms-appx:/// scheme) pointing to the image within the app package.

    Note for JavaScript developers: When using WinRT in JavaScript, method and property names use camelCase, and asynchronous methods return a Promise instead of using the C# await keyword.

    // Check if WinRT is supported on the device
    if (window.Windows) {
    
        // WinRT namespaces
        var SecondaryTile = Windows.UI.StartScreen.SecondaryTile;
        var Uri = Windows.Foundation.Uri;
        var Colors = Windows.UI.Colors;
    
        // Construct secondary tile and add required properties
        var tile = new SecondaryTile();
        tile.tileId = new Date().getTime();
        tile.displayName = "Secondary app tile";
        tile.arguments = "Args to pass for app activation";
        tile.visualElements.square150x150Logo = new Uri("ms-appx:///images/Square150x150Logo.png");
    
        // Specify some options
        tile.visualElements.showNameOnSquare150x150Logo = true; // Default is false
        tile.visualElements.backgroundColor = Colors.red; 
    
        // Ask the user to pin the tile
        var result = tile.requestCreateAsync().done(function () {
            // Handle success and error conditions
        });
    }
  8. Enable Cortana voice commands in a web app

    master

    To integrate Cortana voice commands into your web application, you must provide a Voice Command Definition (VCD) file. A VCD is an XML file that maps specific voice phrases to application actions (such as launching the app or navigating to a specific page).

    To register the VCD file, add a <meta> element to your HTML page that points to the URL of your XML file. When the web app is loaded, Windows automatically downloads and registers the definition.

    <meta name="msapplication-cortanavcd" content="https://contoso.com/vcd.xml"/>
  9. Use the Web authentication broker for online identity providers

    master

    To handle login flows for users using online identity providers (such as those using OpenID or OAuth), you can use the Web authentication broker. This is achieved by specifying start and end URIs within a <meta> tag on an HTML page in your Progressive Web App (PWA).

    Windows detects these URIs and passes them to the Web authentication broker to manage the authentication and authorization process.

    URI Configuration

    • Start URI: The address where you send the authentication request to your provider. This must include required parameters such as client_id, redirect_uri, and response_type. The specific parameters required depend on your identity provider.
    • End URI: The address the user is sent to after the authentication flow is completed.
    <meta name="ms-webauth-uris" content="https://<providerstartpoint>?client_id=<clientid>&response_type=token, https://<appendpoint>"/>
  10. Update .appxmanifest for StartupTask extension

    master

    To enable automatic launching, you must add the uap5 namespace and the StartupTask extension to your PWA's Universal Windows app project's .appxmanifest file.

    Required Attributes:

    • TaskId: The unique ID for the startup task. You will use this exact string in your JavaScript code to access the StartupTask API.
    • DisplayName: The name of your PWA as it should appear in the Windows Task Manager.

    Note: The StartPage attribute is required by the schema but is not currently used.

    <Package ... xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" IgnorableNamespaces="... uap5">
    ...
    <Application>
        ...
        <Extensions>
            <uap5:Extension Category="windows.startupTask" StartPage="">
                <uap5:StartupTask
                TaskId="Startup"
                DisplayName="The name of your app"/>
            </uap5:Extension>
        </Extensions>
    </Application>
  11. Manage frequent items and MRU lists in jump lists

    master

    You can populate the system-managed Recent or Frequent jump list groups by managing files.

    Add a file to the Most Recently Used (MRU) list

    Use StorageItemMostRecentlyUsedList.add() to track files. This allows them to appear in the Recent group.

    function addFile(fileName)
    {
        var localFolder = Windows.Storage.ApplicationData.current.localFolder;
        var AccessCache = Windows.Storage.AccessCache;
    
        localFolder.tryGetItemAsync(fileName).done(function (file) {
            if (file == null) {
                localFolder.createFileAsync(fileName).done(function (newFile) {
                    AccessCache.StorageApplicationPermissions.mostRecentlyUsedList.add(newFile, "", AccessCache.RecentStorageItemVisibility.appAndSystem);
                });
            }
        });
    }

    Enable the Frequent group

    To show files under the Frequent group, set the systemGroupKind on the loaded jump list to JumpListSystemGroupKind.frequent and save.

    Handle file activation from jump lists

    When a user selects a file from a jump list, the WebUIApplication.activated event is triggered with ActivationKind.file. You can access the file details via WebUIFileActivatedEventArgs.

    Windows.UI.WebUI.WebUIApplication.addEventListener("activated", function (activatedEventArgs) {
        if (activatedEventArgs.kind == Windows.ApplicationModel.Activation.ActivationKind.file &&
            activatedEventArgs.length > 0 &&
            activatedEventArgs[0].files.length > 0) {
            // Open the selected file: activatedEventArgs[0].files[0].name
        }
    });
    var StartScreen = Windows.UI.StartScreen;
    
    StartScreen.JumpList.loadCurrentAsync().done(function (jumpList) {
        jumpList.systemGroupKind = StartScreen.JumpListSystemGroupKind.frequent;
        jumpList.saveAsync();
    });