Language: JavaScript and HTML | VB/C#/C++ and XAML

Quickstart: Pinning a secondary tile (Windows Runtime apps using JavaScript and HTML)

Applies to Windows and Windows Phone

Note  Not using JavaScript? See Quickstart: Pinning a secondary tile (Windows Store apps using C#/VB/C++ and XAML).

A secondary tile allows direct access to a specific location or experience inside an app. Examples include an individual friend in a social media app, a particular photo album in a photo app, a saved game, or a playlist in a music app. When the user selects the secondary tile, it launches the parent app with a focus on the pinned content. Apps control what can be pinned as a secondary tile, but pinning is generally a user action. At the least, the user must explicitly confirm before a secondary tile is created. Pinning is most commonly offered through an option in the app bar. For more detailed information on secondary tiles, see the Secondary tiles overview.

This topic walks you through the steps to create a secondary tile for an app and pin it to the Start screen. For instructions on how to copy secondary tiles across devices, see Quickstart: Sending a notification to a secondary tile.

To see the code supplied in this topic used in a full sample, see the Secondary tiles sample. The sample is provided in JavaScript, C#, C++, and Visual Basic versions.

Note  While the procedure outlined in this topic can be applied to Windows Phone 8.1, there are some behavioral differences to be aware of when working with secondary tiles on the phone:

  • The user is not asked to confirm the pinning action.
  • The user cannot rename the secondary tile, nor is asked to choose a size for the secondary tile. The secondary tile always pins as a medium tile and then can be resized by the user.
  • When the secondary tile is pinned, the main app is suspended and you are taken to the Start screen where the secondary tile is shown. Your code should account for this, as it can result in any code that follows the pin request not to be run. For more information, see SecondaryTile.requestCreateAsync.
  • In addition to the regular colors, the background color can be set to "transparent".
  • Default size is ignored.
  • The display name and small logo are ignored.
  • Secondary tiles are not shown in the Apps list.

Prerequisites

To understand this topic, you will need:

Instructions

1. Add a "Pin to Start" button to your app bar (Windows only)

When you pin a secondary tile, you create it and display it on the Start screen. Normally, you let the user pin the app through a Pin to Start button in the app bar. For information on creating an app bar, see Quickstart: Adding an app bar with commands.

The following example declares an app bar and adds a button to it—we'll provide details such as an icon and label later. We assign the app bar an ID of "pinUnpinFromAppbar" and the button an ID of "commandButton".



<div id="pinUnpinFromAppbar" data-win-control="WinJS.UI.AppBar" data-win-options="">
    <button 
        data-win-control="WinJS.UI.AppBarCommand" 
        data-win-options="{id:'commandButton',section:'global'}">
    </button>
</div>

2. Provide a unique ID for your secondary tile



var appbarTileId = "SecondaryTile.AppBar";

3. Choose whether the pin or unpin button should appear on the app bar

Your pin button's action toggles between pinning and unpinning the secondary tile. In this example, we create a function to set the button appropriately. This function will be called first as part of your app's initialization code, and subsequently from the pin button's click handler.

The function checks whether the specified secondary tile exists (is pinned), by using the ID variable appbarTileId we defined in the last step. If the tile exists, the button becomes an unpin button. If not, the button becomes a pin button. The final line in this function sets the app bar's WinJS.UI.sticky property to false, which allows the app bar to be dismissed.

Note that this code overrides the pin and unpin button labels with the standard text we recommend. Without this step, the button text would be simply "Pin" and "Unpin".



function setAppbarButton() {
    var appBar = document.getElementById("pinUnpinFromAppbar").winControl;
    var commandButton = appBar.getCommandById("commandButton").winControl;

    if (Windows.UI.StartScreen.SecondaryTile.exists(appbarTileId)) {
        // Step 2: the tile exists, so set the command label to unpin and the appropriate icon:
        commandButton.label = "Unpin from Start";
        commandButton.icon = "unpin";
        commandButton.tooltip = "Unpin from Start";
    } else {
        // Step 2b: the tile does not exist, so set the command label to pin and the appropriate icon:
        commandButton.label = "Pin to Start";
        commandButton.icon = "pin";
        commandButton.tooltip = "Pin to Start";
    }

    appBar.sticky = false;
}

4. Initialize the app bar and add an event handler for the pin button

Call the code shown in this step, together with any other initialization you need to perform, as part of your app's initialization code each time the app is launched. This code first binds content to the elements on the page. Then it ensures that the pin button is visible, calls the function we defined in the last step to determine whether to show the pin or the unpin button, and assigns the event handler appbarButtonClicked to the pin button's click event. We'll implement the event handler later.



document.getElementById("pinUnpinFromAppbar").disabled = false;
setAppbarButton();

id("commandButton").addEventListener("click", appbarButtonClicked, false);

5. Create a pin function

This example implements a single function that can be called by the pin button's click event handler. This function collects several steps that lead to the pin request:

  • Assigns property values that are required for secondary tile creation
  • Creates the secondary tile object
  • Specifies additional properties of the secondary tile
  • Gets the screen coordinates used to display the confirmation flyout

We'll call this function pinByElementAsync. Its parameters include the button object, the unique ID to assign to the secondary tile, and the short and display names to use with the tile.



function pinByElementAsync(element, newTileID, newTileShortName, newTileDisplayName)

Some of the properties of the secondary tile must be set before it can be pinned. If you attempt to pin a secondary tile without one or more of these properties, the attempt will fail. These are the required properties:

  • A unique ID for the tile
  • Short name (Windows 8 only, not used otherwise)
  • Display name
  • Tile options
  • A logo image
  • An argument string that will be passed to the parent application when the secondary tile is activated

In this example, we define only the tile options, logo image, and argument string. The other required property values were supplied as parameters in the function call (newTileID, newTileShortName, and newTileDisplayName). As an example argument string, this sample passes the time the secondary tile was pinned to the Start screen.

Note  If you provide the same ID as that of an existing secondary tile, the existing secondary tile will be overwritten.



var currentTime = new Date();
var TileActivationArguments = newTileID + " was pinned at " + currentTime;

var newTileOptions = Windows.UI.StartScreen.TileOptions.showNameOnLogo;
var uriLogo = new Windows.Foundation.Uri("ms-appx:///images/SecondaryTileDefault-sdk.png");

Next, we create the secondary tile object. This version of the constructor creates a medium tile. Note that if your secondary tile receives notifications, it is a best practice to declare all tile sizes. This is done by providing logo images through SecondaryTileVisualElements.



var tile = new Windows.UI.StartScreen.SecondaryTile(newTileID, newTileShortName, newTileDisplayName, TileActivationArguments, newTileOptions, uriLogo);

Now that you have a secondary tile object, you can specify secondary tile properties that are not set through the constructor. This example specifies the foreground text color and small logo.



tile.foregroundText = Windows.UI.StartScreen.ForegroundText.light;
tile.smallLogo = new Windows.Foundation.Uri("ms-appx:///images/smallLogoSecondaryTile-sdk.png");

The user must confirm before a secondary tile is pinned. The flyout that asks for this confirmation should be displayed near the button that invoked the pin request. This example retrieves the bounding rectangle of our previously defined pin button with the ID "commandButton". The "document" object is the HTML document.



var element = document.getElementById("commandButton")
var selectionRect = element.getBoundingClientRect();

Next, the function requests that the secondary tile be pinned. Remember that this call does not actually pin the tile to the Start screen. Instead, it displays the confirmation flyout that asks the user for permission to do so. Using the bounding rectangle of the pin button, this example displays the confirmation flyout above those coordinates. On approval, Windows creates the secondary tile and places it on the Start screen.

The call to pin the tile returns as a Promise object, which allows the pinByElementAsync function to be called asynchronously.



var buttonCoordinates = { x: selectionRect.left, y: selectionRect.top, width: selectionRect.width, height: selectionRect.height };
var placement = Windows.UI.Popups.Placement.above;

return new WinJS.Promise(function (complete, error, progress) {
    tile.requestCreateForSelectionAsync(buttonCoordinates, placement).done(function (isCreated) {
        if (isCreated) {
            complete(true);
        } else {
            complete(false);
        }
    });
});

The full pinByElementAsync function is shown here.



function pinByElementAsync(element, newTileID, newTileShortName, newTileDisplayName) {
    var uriLogo = new Windows.Foundation.Uri("ms-appx:///images/SecondaryTileDefault-sdk.png");
    var uriSmallLogo = new Windows.Foundation.Uri("ms-appx:///images/smallLogoSecondaryTile-sdk.png");
    var newTileOptions = Windows.UI.StartScreen.TileOptions.showNameOnLogo;

    var currentTime = new Date();
    var TileActivationArguments = newTileID + " was pinned at " + currentTime;

    var tile = new Windows.UI.StartScreen.SecondaryTile(newTileID, newTileShortName, newTileDisplayName, TileActivationArguments, newTileOptions, uriLogo);

    tile.foregroundText = Windows.UI.StartScreen.ForegroundText.light;
    tile.smallLogo = uriSmallLogo;

    var selectionRect = element.getBoundingClientRect();
    var buttonCoordinates = { x: selectionRect.left, y: selectionRect.top, width: selectionRect.width, height: selectionRect.height };
    var placement = Windows.UI.Popups.Placement.above;
    
    return new WinJS.Promise(function (complete, error, progress) {
        tile.requestCreateForSelectionAsync(buttonCoordinates, placement).done(function (isCreated) {
            if (isCreated) {
                complete(true);
            } else {
                complete(false);
            }
        });
    });
}

6. Create an unpin function

When the secondary tile is already pinned, the pin button becomes an unpin button and the button's click event handler unpins the tile. This example provides the function that the handler calls to unpin the tile. As parameters, the function accepts the pin button object, again for the purpose of placing the confirmation flyout, and the secondary tile's unique ID. As in the pin function, the unpin call returns a Promise object.

Note  Any secondary tile can also be unpinned through the Start screen app bar. You have the option of relying on that method for unpinning, in which case you don't need to implement unpin functionality or provide an unpin button.



function unpinByElementAsync(element, unwantedTileID) {

    var selectionRect = element.getBoundingClientRect();
    var buttonCoordinates = { x: selectionRect.left, y: selectionRect.top, width: selectionRect.width, height: selectionRect.height };
    var placement = Windows.UI.Popups.Placement.above;

    var tileToDelete = new Windows.UI.StartScreen.SecondaryTile(unwantedTileID);
    
    return new WinJS.Promise(function (complete, error, progress) {
        tileToGetDeleted.requestDeleteForSelectionAsync(buttonCoordinates, placement).done(function (isDeleted) {
            if (isDeleted) {
                complete(true);
            } else {
                complete(false);
            }
        });
    });
}

7. Implement the event handler for your button

When the user selects your button on the app bar, a flyout asks the user for confirmation. To make sure that the app bar isn't dismissed while the flyout is showing, you must set the app bar's WinJS.UI.sticky property. Also, make sure that the parent of your flyout is correctly assigned. This example calls the setAppbarButton, pinByElementAsync, and unpinByElementAsync functions we defined in the previous steps.

Note that the handler calls setAppbarButton for both success and failure cases in both pinning and unpinning operations. If the operation was successful, the button will swap between pin and unpin. If the operation failed, the button will remain as it is. In both cases, the function must be called to revert the WinJS.UI.sticky property to false so that the app bar can be dismissed.



function appbarButtonClicked() {
    document.getElementById("pinUnpinFromAppbar").winControl.sticky = true;

    if (WinJS.UI.AppBarIcon.unpin === document.getElementById("commandButton").winControl.icon) {
        unpinByElementAsync(document.getElementById("commandButton"), appbarTileId).done(function (isDeleted) {
            if (isDeleted) {
                WinJS.log && WinJS.log("Secondary tile was successfully unpinned.", "sample", "status");
                setAppbarButton();
            } else {
                WinJS.log && WinJS.log("Secondary tile was not unpinned.", "sample", "error");
                setAppbarButton();
            }
        });
    } else {
        pinByElementAsync(document.getElementById("commandButton"), appbarTileId, "App bar pinned secondary tile", "A secondary tile that was pinned by the user from the app bar").done(function (isCreated) {
            if (isCreated) {
                WinJS.log && WinJS.log("Secondary tile was successfully pinned.", "sample", "status");
                setAppbarButton();
            } else {
                WinJS.log && WinJS.log("Secondary tile was not pinned.", "sample", "error");
                setAppbarButton();
            }
        });
    }
}

Summary and next steps

In this Quickstart, you defined a button on an app bar with which a user could pin or unpin a secondary tile. You created the secondary tile, defined many of its properties, and presented the confirmation dialog to the user that results in the final addition of the secondary tile to the Start screen.

After a secondary tile is pinned, the parent app tile then creates a channel Uniform Resource Identifier (URI) so that it can communicate with the secondary tile. For more information, see Quickstart: Sending a notification to a secondary tile.

Related topics

Secondary tiles sample
Secondary tiles overview
Quickstart: Sending a notification to a secondary tile
Guidelines and checklist for secondary tiles
SecondaryTile class

 

 

Show:
© 2014 Microsoft. All rights reserved.