How to share text (HTML)
[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]
Sharing text is one of the most basic, yet essential, methods for sharing content. We recommend your app support sharing text:
- When you want the content to be available to a large number of target apps.
- As a secondary source when sharing links or sharing HTML.
What you need to know
Technologies
Prerequisites
- You should be familiar with Visual Studio and its associated templates.
- You should be familiar with JavaScript.
Instructions
Step 1: Set up your app as a share source
Add a DataRequested event handler to fire when the user wants to invoke Share. In a Windows Store app, this occurs automatically when the user invokes the Share charm. If you're developing for Windows Phone, there is no built-in Share charm, so you'll need to add a control for the user to tap and trigger the handler.
var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
dataTransferManager.addEventListener("datarequested", shareTextHandler);
The remaining steps implement the shareTextHandler
function.
Step 2: Get a DataRequest object
When a datarequested event occurs, your app receives a DataRequest object. This object contains a DataPackage that you can use to provide the content that the user wants to share.
var request = e.request;
Step 3: Set the title and description properties
request.data.properties.title = "Share Text Example";
request.data.properties.description = "Demonstrates how to share.";
Step 4: Add the text to the DataPackage
To add text, use the setText method.
request.data.setText("Hello World!");
Complete example
Here's an example of a function that sets some text for a user to share. For a more complete example, check out our code gallery sample.
function shareTextHandler(e) {
var request = e.request;
request.data.properties.title = "Share Text Example";
request.data.properties.description = "Demonstrates how to share.";
request.data.setText("Hello World!");
}
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// This app is newly launched. Register the app as share source.
var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
dataTransferManager.addEventListener("datarequested", shareTextHandler);
} else {
// TODO: This app was reactivated from suspension.
// Restore the app state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
Related topics
Sharing content source app sample