HtmlFormatHelper HtmlFormatHelper HtmlFormatHelper HtmlFormatHelper Class

Responsible for formatting HTML content that you want to share or add to the Clipboard. Also allows you to get HTML fragments from the content.

Syntax

Declaration

public static class HtmlFormatHelperpublic static class HtmlFormatHelperPublic Static Class HtmlFormatHelper

Remarks

For more information on how to use this class, check out SetHtmlFormat(System.String). You might also want to look at our topic, How to share HTML.

Examples

if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.html)) {
    document.getElementById("htmlContentArea").className = "unhidden";
    
    shareOperation.data.getHtmlFormatAsync().then(function (html) {
        if (html !== null) {
            var htmlFragment = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.getStaticFragment(htmlFormat);

            // Set the innerHTML of the ifram to the HTML fragment.
            var iFrame = document.getElementById("htmlContent");
            iFrame.style.display = "";
            iFrame.contentDocument.documentElement.innerHTML = htmlFragment;
        } 
    });

    // Loop through any images and use the resourceMap to map each image element's src.
    var images = iFrame.contentDocument.documentElement.getElementsByTagName("img");
    if (images.length > 0) {
        shareOperation.data.getResourceMapAsync().done(function (resourceMap) {
            if (resourceMap.size > 0) {
                for (var i = 0, len = images.length; i < len; i++) {
                    var streamReference = resourceMap[images[i].getAttribute("src")];
                    if (streamReference) {
                        // Call a helper function to map the image element's src to a corresponding blob URL generated from the streamReference
                        setResourceMapURL(streamReference, images[i]);
                    }
                }
            }
        });
}
//shareOperation.reportCompleted();

Methods summary

Takes a string that represents HTML content and adds the necessary headers to ensure it is formatted correctly for share and Clipboard operations.

Gets a string that represents an HTML fragment.

Methods

  • CreateHtmlFormat(System.String)
    CreateHtmlFormat(System.String)
    CreateHtmlFormat(System.String)
    CreateHtmlFormat(System.String)

    Takes a string that represents HTML content and adds the necessary headers to ensure it is formatted correctly for share and Clipboard operations.

    public static string CreateHtmlFormat(System.String htmlFragment)public static string CreateHtmlFormat(System.String htmlFragment)Public Static Function CreateHtmlFormat(htmlFragment As System.String) As string

    Parameters

    • htmlFragment
      System.String
      System.String
      System.String
      System.String

      A string representing the HTML content.

    Returns

    • string
      string
      string
      string

      A string representing the formatted HTML.

    Remarks

    Examples

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Windows.ApplicationModel.DataTransfer;
    using Windows.Foundation;
    using Windows.Foundation.Collections;
    using Windows.Storage;
    using Windows.Storage.Streams;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Controls.Primitives;
    using Windows.UI.Xaml.Data;
    using Windows.UI.Xaml.Input;
    using Windows.UI.Xaml.Media;
    using Windows.UI.Xaml.Navigation;
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace ShareMainBetaCS
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class ShareHTML : Page
        {
            public ShareHTML()
            {
                this.InitializeComponent();
                this.ShareSourceLoad();
            }
    
            // <SnippetHowToShareHtml_CS>
            public void ShareSourceLoad()
            {
                DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
                dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.DataRequested);
            }
    
            async void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
            {
                string htmlExample = "<p>Here is our store logo: <img src='assets/logo.png'>.</p>";
                string fileExample = "assets\\logo.png";
                // <SnippetGetFileForMap_CS>
                RandomAccessStreamReference streamRef = null;
                Windows.Storage.StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileExample);
                try
                {
                    streamRef = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(file);
                }
                catch (Exception ex)
                {
                    // TODO: Handle the exception.
                }
                // </SnippetGetFileForMap_CS>
                // <SnippetFormatHtml_CS>
                string htmlFormat = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.CreateHtmlFormat(htmlExample);
                // </SnippetFormatHtml_CS>
                DataRequest request = e.Request;
                request.Data.Properties.Title = "Share HTML Example";
                request.Data.Properties.Description = "An example of how to share HTML.";
                // <SnippetSetHtmlFormat_CS>
                request.Data.SetHtmlFormat(htmlFormat);
                // </SnippetSetHtmlFormat_CS>
                // <SnippetSetResourceMap_CS>
                request.Data.ResourceMap[fileExample] = streamRef;
                // </SnippetSetResourceMap_CS>
            }
            // </SnippetHowToShareHtml_CS>
    
            /// <summary>
            /// Invoked when this page is about to be displayed in a Frame.
            /// </summary>
            /// <param name="e">Event data that describes how this page was reached.  The Parameter
            /// property is typically used to configure the page.</param>
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
        }
    }
    
    function shareHtmlHandler(e) {
        var request = e.request;
        var htmlExample = "<p>Here is our store logo: <img src='images/logo.png'>.</p>";
        var localImage = "images\\logo.png";
        request.data.properties.title = "Share Html Example";
        request.data.properties.description = "A demonstration that shows how to share an HTML fragment with a local image.";
        var deferral = e.request.getDeferral();
        Windows.ApplicationModel.Package.current.installedLocation.getFileAsync(localImage).done(function (imageFile) {
            request.data.setHtmlFormat(Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.createHtmlFormat(htmlExample));
            request.data.resourceMap[localImage] = Windows.Storage.Streams.RandomAccessStreamReference.createFromFile(imageFile);
            deferral.complete();
        }, function (err) {
            request.failWithDisplayText(err);
        });
    }
    
  • GetStaticFragment(System.String)
    GetStaticFragment(System.String)
    GetStaticFragment(System.String)
    GetStaticFragment(System.String)

    Gets a string that represents an HTML fragment.

    public static string GetStaticFragment(System.String htmlFormat)public static string GetStaticFragment(System.String htmlFormat)Public Static Function GetStaticFragment(htmlFormat As System.String) As string

    Parameters

    • htmlFormat
      System.String
      System.String
      System.String
      System.String

      The formatted HTML.

    Returns

    • string
      string
      string
      string

      An HTML fragment based on the formatted HTML.

    Remarks

    As a security precaution, you shouldn't display HTML unless you're sure it doesn't have any dynamic content. You can use the GetStaticFragment method to get shared HTML content without any dynamic elements such as script tags.

    Examples

    if (shareOperation.data.contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.html)) {
        document.getElementById("htmlContentArea").className = "unhidden";
        
        shareOperation.data.getHtmlFormatAsync().then(function (html) {
            if (html !== null) {
                var htmlFragment = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.getStaticFragment(htmlFormat);
    
                // Set the innerHTML of the ifram to the HTML fragment.
                var iFrame = document.getElementById("htmlContent");
                iFrame.style.display = "";
                iFrame.contentDocument.documentElement.innerHTML = htmlFragment;
            } 
        });
    
        // Loop through any images and use the resourceMap to map each image element's src.
        var images = iFrame.contentDocument.documentElement.getElementsByTagName("img");
        if (images.length > 0) {
            shareOperation.data.getResourceMapAsync().done(function (resourceMap) {
                if (resourceMap.size > 0) {
                    for (var i = 0, len = images.length; i < len; i++) {
                        var streamReference = resourceMap[images[i].getAttribute("src")];
                        if (streamReference) {
                            // Call a helper function to map the image element's src to a corresponding blob URL generated from the streamReference
                            setResourceMapURL(streamReference, images[i]);
                        }
                    }
                }
            });
    }
    //shareOperation.reportCompleted();
    

Device family

Windows 10 (introduced v10.0.10240.0)

API contract

Windows.Foundation.UniversalApiContract (introduced v1)

Attributes

Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.DualApiPartitionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute

Details

Assembly

Windows.ApplicationModel.DataTransfer.dll