Tag Archives: HWA

UWP Hosted Web App on Xbox One (App Dev on Xbox series)

For the fourth installment in the series, we are open sourcing yet another sample app: South Ridge Video, an open source video app developed as a hosted web application built with React.js and hosted on a web server. South Ridge can easily be converted to a UWP application that takes advantage of native platform capabilities and can be distributed through the Windows Store as any other UWP app. The source code is available on GitHub right now, so make sure to check it out.

If you missed the previous blog post from last week on Background Audio and Cross Platform Development with Xamarin, make sure to check it out. We covered how to build a cross-device music experience using Xamarin and how to support background audio on the Universal Windows Platform, including the Xbox One. To read the other blog posts and watch the recordings from the App Dev on Xbox live event that started it all, visit the App Dev on Xbox landing page.

South Ridge Video

image1

What if you could extend the investment put into your web application and make it available as an Xbox One Windows Store app? What if you could also continue to use your existing web frameworks, CDN and server backend, yet still be able to use native Windows 10 APIs?

You can! A Hosted Web App (HWA) is a web app that can be submitted to the Store just like any other Universal Windows Platform (UWP) app. Since you’ve already invested in the development of the web app, your transformation into a HWA can be done rather quickly and easily.

To do this, you’ll reuse your existing code and frameworks as if you were developing for the browser. Let’s take a look at the South Ridge Video example app on GitHub. This is an app built with React.js and uses a web server back-end.  The application is delivered by the server when the app is launched and the UWP app will host that web content.

However, the HWA is not just a simple wrapper; you can also call into native Windows 10 APIs, such as adding an event to the user’s calendar. You can even use APIs such as toast notifications and camera capture or media transport controls with background audio. Note that when accessing sensitive APIs, make sure you declare the required App Capability in the appmanifest.

Now that your web app is ready and you want to turn it into a HWA, let’s take a look at the things you need to do to get it ready for Windows Store distribution to Xbox One.

Local Testing on a retail Xbox One

First, you need to put your retail Xbox One into developer mode so you can deploy and test the app. This is pretty straightforward; it involves installing an app from the Windows Store. Go here to see the steps on how to activate dev mode and how it works.

Now that you have your Xbox ready for deployment, let’s review the ways you can generate the app. There are three main options:

  • Using a web browser-based tool, such as Windows App Studio, to generate it for you
  • On a Mac or PC using Manifold.js
  • On a PC using Visual Studio

Let’s drill down into each option to see which best fits your needs.

Windows App Studio

Let’s start with the browser-based option, using Windows App Studio to create the HWA. Windows App Studio is a free online app creation tool that allows you to quickly build Windows 10 apps.

  1. Open Windows App Studio in your web browser.
  2. Click Start now!
  3. Under Web app templates, click Hosted Web App.
  4. Follow the on-screen instructions to generate a package ready for publishing to the Windows Store.
  5. You can then download the generate package that you’ll publish to the Store.

On a Mac using Manifold.js

What you need:

  • A web browser
  • A command prompt

ManifoldJS is a Node.js app that easily installs from NPM. It takes the meta-data about your web site and generates native hosted apps across Android, iOS and Windows. If your site does not have a web app manifest, one will be automatically generated for you. For example, take a look at the web app manifest for South Ridge Video.

  1. Install NodeJS, which includes NPM (Node Package Manager)
  2. Open a command prompt and type “NPM install -g manifoldJS”
    1. npm install -g manifoldjs
  3. Run themanifoldjs command on your web site URL:
    1. manifoldjs http://southridge.azurewebsites.net
  4. Follow the steps in the video below to complete the packaging (and publish your Hosted Web App to the Windows Store)

image2

A couple notes about using Manifold.js

  • If you have a W3C manifest, it will use that for app info; otherwise, it will be created automatically.
  • Use the -windows10 platform flag to generate only for UWP.

On a Windows PC using Visual Studio

What you need:

  • Visual Studio 2015. The free, full-featured Visual Studio Community 2015 includes Windows 10 developer tools, universal app templates, a code editor, a powerful debugger, Windows Mobile emulators, rich language support and much more—all ready to use in production. The same is true for Professional or Enterprise variants of VS 2015.
  • (Optional) Windows Standalone SDK for Windows 10. If you are using a development environment other than Visual Studio 2015, you can download a standalone Windows SDK for Windows 10 installer. Note that you do not need to install this SDK if you’re using Visual Studio 2015 Update 3; it is already included.

Steps to create the HWA (go here to see all these steps with screenshots):

  • Pick the website URL and copy it into your clipboard.
  • Launch Visual Studio 2015.
    1. Click File.
    2. Click New Project.
    3. Under JavaScriptthen Windows Universal, click Blank App (Windows Universal).
  • Delete the VS project template generated code.
    1. Since this is a hosted web app where the content is served from a remote server, you will not need most of the local app files that come with the JavaScript template by default. Delete any local HTML, JavaScript, or CSS resources. All that should remain is theappxmanifest file, where you configure the app and the image resources.
  • Open the appxmanifestfile.
    1. Under the Application tab, find the Start page text field.
    2. Replace html with your website URL.
  • Set the boundaries of your app.
    1. Application Content URI Rules (ACURs) specify which remote URLs are allowed access to your app and to the Universal Windows APIs. At the very minimum, you will need to add an ACUR for your start page and any web resources utilized by that page. For more information on ACURs, click here.
    2. Open theappxmanifest file.
    3. Click theContent URIs.
    4. Add any necessary URIs for your start page.

For example:

  1. 1. http://southridge.azurewebsites.net2. http://*.azurewebsites.net
  2. Set theWinRT Access to All (for each URI you added).
  • At this point, you have a fully functioning Windows 10 app capable of accessing Universal Windows APIs! You can now deploy to the Xbox One using the remote debugger as if it were any Windows 10 remote device, or you can use the Device Portal (covered in the next section).

Installing your HWA on the Xbox One for local testing

At this point, you now have an app package (APPX) or a manifest folder (Manifold.js), containing the files you need to install or publish your application. You can “side-load” your HWA to the Xbox by using the Device Portal (go here for more information about the Device Portal for Xbox One). One you’ve logged into the portal, you can then deploy your app.

APPX Deployment (Visual Studio / App Studio)

Here are the steps (go here to see these steps below with screenshots):

  1. Go to the Apps tab on the portal.
  2. You’ll see two buttons to upload items to the device: App Package and Dependencies.
  3. Tap the App Package button and navigate to the package folder you generated for your app. In there, you’ll find an appx file. Select that file and upload it.
  4. Now tap the Dependencies button, navigate again to your package folder and drill down to the dependencies sub folder. This contains the dependencies that your app needs to run – upload each one in the folder. (Note that you only need to do this when deploying via the Portal. Visual Studio delivers dependencies when remote debugging and the end user’s machine will already have these installed when delivered via the Store.)
  5. With the app package and the dependencies uploaded, click the Go button under the “Deploy” section and the app will be installed.
  6. Now go to the Xbox and launch the app!

Loose Files Deployment (Manifold.js)

The only difference between deploying an app packages with Manifold.js is that you have “loose” files instead of an APPX package. In the steps above, instead of uploading an APPX and Dependencies, you choose the “upload loose files” option and select the manifest folder. The portal will look in that folder for the manifest file and gather all the required pieces to complete the installation.

Design and User Experience Considerations for Xbox One apps

Designing for the “10-Foot Experience”

Xbox One is considered a “10-foot experience”, meaning that your users will likely be sitting a minimum of 10 feet away from the screen. You’ll want to consider the app’s ability to be used at that distance as opposed to being accessed within a web browser, from two feet away, with a mouse and keyboard. This article explains how to make sure you get the best user experience for the 10-foot experience scenario.

Designing for TV and understanding the “TV SafeZone”

Television manufacturers will apply a “safe-zone” around the content that can clip your app. By default, we apply a safe border around your app to account for this, however you can ensure that your app takes the full screen size using following code:


var applicationView = Windows.UI.ViewManagement.ApplicationView.getForCurrentView();
applicationView.setDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow);

Understanding and managing XY focus and navigation

You’ll want to consider your app’s ability to handle XY navigation by the user and disable the “Mouse Mode” that’s turned on by default for UWP apps. This is important because users’ main input method for Xbox One is a handheld controller. See here for more on how to work with XY focus and navigation. Use the following code to enable XY navigation using JavaScript:


navigator.gamepadInputEmulation = "keyboard";

To enable directional navigation, you can use the TVJS library which is discussed below.

Considering your app’s appearance when another app is snapped

When users run an app on Xbox One, a second app may be ‘snapped’ to the right of the main app. When this is the case, the main app is considered to be in Fill Mode. While testing your app, open Cortana or another ‘snappable’ app to see how your app appears. You want to make sure your UI is still usable and has a graceful transition between Full Screen and Fill Mode. Implement an adaptive UI to make sure the user has the best experience for this scenario.

Integrate with the System Media Controls

If your app is a media app, it is important that your app responds to the media controls initiated by the user via the on-screen buttons, Cortana (typically through speech), the System Media Transport Controls in the nav pane or the Xbox and SmartGlass apps on other devices. Take a look at the MediaPlayer control from TVJS which automatically integrates with these controls or check out how to manually integrate with the System Media Transport Controls.

TVJS

TVJS is a collection of helper libraries that make it easier to build web applications for the TV. If you are building a hosted web app that will also run on the Xbox, TVJS can help add support for Directional navigation, as well as provide several controls that make it easier to interact with content on the TV.

DirectionalNavigation

Directional navigation is a feature that provides automatic two-dimensional navigation within the pages of your TV app. Apps won’t need to trap and handle navigation within their pages, or to explicitly specify all the valid focus targets for each element in the UI. With automatic focus handling, users can navigate around in an intuitive and robust way.

When users enter directional input to move from one element to another, the automatic focus algorithm looks at the set of potential focus targets, determines the next element to move to and then automatically sets the focus to that element. To determine the element to move to, the algorithm combines directional input, past focus history, and the physical layout of UI elements on the page.

To enable directional navigation, include the following script reference:

<script src=”directionalnavigation-1.0.0.0.js”></script>

By default, only a, button, input, select, and text area elements are considered focus-able. To make other elements focus-able, set a valid tab index on the element.

<div tabindex=”0″>This div is eligible for focus</div>

Make sure to check out the documentation to learn how to change the root element, set initial focus, how to override next focus, best ways to optimize controls for focus and how to customize the input. Don’t miss the samples as well that go through a lot of great examples.

Submitting your app to the Windows Store

Once you’re happy with the app after testing it on Xbox, it’s time to publish it to the Windows Store!

Depending on which route you took to build the app, the process is a little different on how you build the package for Store submission.

Xbox One and Hosted Web Apps are a great way to deliver your web application to millions of Xbox One users and enter the living room experience with minimal effort.

Wrap up

Make sure to check out the app source on our official GitHub repository, read through some of the resources provided, watch the event if you missed it and let us know what you think through the comments below or on twitter.

Next time we will release another app experience and go in-depth on how to build great Internet of Things experiences using the Universal Windows Platform and how to make them shine on the Xbox One.

Until then, happy coding!

Resources for Hosted Web Apps

Download Visual Studio to get started!

The Windows team would love to hear your feedback.  Please keep the feedback coming using our Windows Developer UserVoice site. If you have a direct bug, please use the Windows Feedback tool built directly into Windows 10.

— Written by Jeff Burtoft, Principle Program Manager WDG/PAX

Windows App Studio June ’16 Release: Harnessing the wealth of the web with the new REST API Data Source

There are two things we love most here on the Windows App Studio team: First, we love adding new features that increase the capabilities of the apps you can create. Second, we love when we can deliver on your requests. With that in mind, we’re quite excited about today’s release because it enables a ton of new capabilities, and more importantly, we’re delivering on some of your longest standing requests for new features.

This massive update also provides a bit of insight into where we want to take Windows App Studio going forward. We spent a lot of time this year thinking about how we can provide the best value to you through this tool, and we came to the conclusion that helping you bring the wealth internet services into your UWP apps (with no coding!) and giving you multiple outlets to share your apps is the best place to start.

Here at Windows App Studio, we have the philosophy that anyone should be able to create an app, and that coding knowledge shouldn’t necessarily be a barrier to that. Creating documents on the computer was far more complex when the technology was introduced decades ago, but now it’s easier than ever (especially with Office365) and the use cases for documents are plentiful to the point where everyone has reasons to make them. Apps, especially Universal Windows Platform apps, should enjoy that same future. What was once complex should become easy and the use cases of apps should become far broader than they are today.

Today’s release represents an early step in our promise to you to bring the best of the world of apps to you, in an easy and fast way, so you can create with the minimal limits possible. Check out the new release here.

The New REST API Data Source

The major feature we’re releasing today is a REST API Data Source, which is one the most requested features in the history of Windows App Studio. Much like the current RSS Data Source, this feature is open ended, meaning you can connect it to almost any open REST API service available on the internet. REST APIs are the backbone of how data gets passed around the web. If these are new concepts to you, an easy way to think about it is that APIs (Application Programming Interfaces) let different pieces of software talk to one another and REST (Representational State Transfer) is an architecturally structured way of “packaging” those data communications.

For the first version of this release, we’re supporting GET commands for REST APIs (meaning it only pulls information) and have support for headers, as well. This data source is more complex than others, so we have a post with instructions on how to use it posted on our Windows App Studio blog, which you can find here.

There are REST APIs available for almost any type of data and almost every major service has an API for developers. For example, if you want to add event/concert listings to your app, you can use an API from a service like SeatGeek or SongKick to pull in event information for a region or filter you specify. The app you generate with this data will stay up to date each time it’s opened and makes a new request for data.

1_restAPI

We plan to do a lot more work to this feature going forward to make it more powerful and a lot easier to use and provide easier integrations for the most popular REST APIs. The current state of the feature is definitely more complex than it will be going forward, but can be used by a non-developer right now without any major issues. So play around with it, look up API documentation of the service you’re integrating to make sure the requests are formatted correctly, and remember that you can’t truly break anything, so experiment freely. J

Hosted Web App Capability Declarations

Hosted Web Apps created with Windows App Studio are quite popular as it’s the fastest and easiest way to bring your web app to UWP. Today’s release expands on the feature and lets you declare capabilities of your app, letting you can take advantage of the Windows 10 OS features with your server-side code so your web app can act like a native Windows UWP. You can now enable things like Live Tiles, Notifications, Cortana, and a lot more.

2_capabilities

This release also includes a massive amount of smaller improvements and features. Since this is already a marathon of a blog post, here are the highlights:

Tool Improvements

Simulator Improvements: Redesigned detail pages, Carousel & Slider View.

Ordering & Paging: Configuration Wizards in Edit Section to allow users to configure ordering and paging in all data sources.

Dark & Light Themes: Revised and improved.

Generated App Improvements

New Shell Control: Improved navigation and nav pane.

New Detail Pages: Improved layouts, better reading and content display taking advantage of HTML Block.

New About page: Improved the About page.

Performance improvements: General improvements for apps. Reduced memory and increased loading speed.

Carousel & Slider View: Updates to these components in generated apps.

Pagination & Infinite Scroll: Allows loading of more content from data sources, removing the fixed number of items (forty) retrieved previously.

Ordering: Allows ordering of the content as established in the app configuration. This also leads to a better experience in Live Tiles (if you have a Live Tile based on a collection ordered by a date field, when you add a new row it will appear in the live tile).

Open Source Library and Control Improvements

The Windows App Studio Libraries have seen healthy adoption since we announced them at //build. We hit the first major milestone of merging a pull request from a member of the Windows App Studio community. The update improved the RSS Data Source so it can now properly handle the “yandex:full-text” property in feeds which are popular in Russia and other countries. Other library improvements are the following:

HtmlBlock: Added a new control to our XAML library that transforms HTML and renders it as XAML, which improves the readability of HTML content in the generated apps as well as the overall application performance.

InfiniteScroll: Created a new control to allow apps to make pagination for a rich user experience.

Animated GIFs:  Included support for Animated GIFs in our ImageEx control.

Carousel Redesign: Improved experience and better UX integration in carousel control.

Slider View: The older small carousel has been improved and got a name change for differentiation

REST API Data Source: The new data source is now in our libraries. This is a general purpose data source able to retrieve content from any REST API service. This data source allows ordering and paging.

Data Sources Ordering & Paging: All data sources now support Ordering & Paging.

Data Sources Language aware.

Other Things

Unfortunately, we have a bit of bad news this release as well. Due to policy changes by Instagram, we were forced to remove the Instagram data source. They no longer want their users’ content accessed outside of their 1st party apps without explicit permission, so they shut off the capability of other apps to consume Instagram content if the apps do not get prior approval. Sadly, this means that all current implementations of the Instagram data source no longer work and should be removed from your apps and projects.

We hope that you love the new features in this Windows App Studio release and we can’t wait to keep up the work and take this tool to the next level. For us to do that best, we need your help. So please let us know your thoughts and requests on the forum and User Voice, and if you’d like to contribute code to the Windows App Studio libraries, please do!  You can find the libraries on our GitHub Page.

Thanks for reading and happy app building!  We can’t wait to see all the creative things you’ll make.

Keeping your Hosted Web App secure

Hosted Web Apps running on Windows 10 benefit from the web platform improvements and updates implemented in Microsoft Edge, the default bowser of Windows 10. That same web platform and its new rendering engine also power Hosted Web Apps.

When it comes to security, this means that developers can use familiar techniques to secure the web content of their Hosted Web App. In other words, the same tools developers would use to secure their apps in the browser can also secure their Hosted Web Apps.

On top of those familiar security features, however, Hosted Web Apps also have a few additional ones to help keep the app secure.

Content Security Policy

When it comes ensuring your web content is kept safe, you have Content Security Policy (CSP). CSP lets you to create a list of sources of trusted content, and instructs the browser to only execute or render resources from those sources. In the context of Hosted Web Apps, CSP can be used to keep the users of your apps protected from cross-site scripting (XSS) on the web.

Why do I need CSP?

You need CSP because the web and its security model are based on the same origin policy concept, under which the browser will permit scripts contained in a web page to access data in another web page but on the condition that both of these web pages have the same origin. That origin is defined as a combination of URI scheme, hostname, and port number.

Primarily, this important security mechanism of same origin policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page’s Document Object Model (DOM). Each origin is kept isolated from the rest of the web, giving developers a safe sandbox in which to build and play.

In layman’s terms: script or code from “https://myweb.com” should only have access to “https://myweb.com’s data, and “https://malicious.com” should not be allowed access. If this wasn’t in place, “https://malicious.com” could attack “https://myweb.com” by injecting some harmful script. This injection attack is called cross-site scripting (XSS).

To help reduce these XSS risks and data injection attacks on modern browsers, W3C’s Web Application Security Working Group came up with the Content Security Policy security layer. CSP achieves this by declaring the dynamic resources that are allowed to load or pass in the Content-Security-Policy HTTP header.

This declarative policy enables you to give the browser a whitelist of locations from which it can load resources from and tell it whether the browser can use inline styles or scripts and dynamic JavaScript evaluation. If there’s an attempt to load a resource from somewhere that isn’t on this whitelist, loading of that resource is blocked.

By default, CSP assumes an opt-in policy. Hence, if you don’t declare otherwise, all inline <style> and <script> tags are blocked.

The HTTP header will look something like:



Content-Security-Policy:    directive;


CSP 1.0 includes the following options for directives:

  • default-src:
  • script-src
  • object-src
  • style-src
  • img-src
  • media-src
  • frame-src
  • font-src
  • connect-src

For example, the following declaration would ensure that all content comes only from the site’s own origin domain:



Content-Security-Policy:    default-src 'self';


This example, on the other hand, allows content from a trusted domain and all of its subdomains, even if it differs from the domain on which the CSP is set:



Content-Security-Policy: default-src 'self' *.mydomain.com


The above examples show how you can deliver CSPs via an HTTP header. However, you can set a policy directly in the markup of a page using meta tags. The following example shows a meta tag with an http-equiv attribute specifying a CSP:



&lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src https://mytrsuteddomain.com; child-src 'self';&quot;&gt; 


As mentioned earlier, Hosted Web Apps are powered by Microsoft Edge’s web platform and thus rely on its implementation of this policy. As per the latest platform status on Edge’s Dev Center page, Microsoft Edge build 10240+ implements Content Security Policy (CSP) 1.0.

1_csp

If you would like to view the Content-Security-Policy implementation on the domain that you are loading into the Hosted Web App, you can use the developer tools on Edge: run the app from Visual Studio and then press F12, which will pop up the F12 Developer Tools. From there, go to “Network” and view the response headers of the calls.

The following screenshot from a sample debugging session shows the CSP applied when the web application tries to load some content from Facebook.

2_FB

For Hosted Web Apps, you can declare a list of allowed/trusted resources/URIs in the Application Content URI Rules (ACURs), which in turn gives remote URLs direct access to Universal Windows Platform (UWP) APIs from remote HTML, CSS, and JavaScript.

CSP also enables you to lock down the page if, for example, you would like to ensure that only the resources written by you get loaded.

A good approach when setting up security is to start with the most restrictive CSP as a default, which will block just about everything using the directive default-src ‘none’, and from there, add any allowed resources (e.g. scripts, images, CSS styles, frames).

In summary, CSP helps you create a safer environment to run scripts (e.g. yours or trusted third parties) against hardware APIs provided by the Universal Windows Platform (UWP).

As a best practice, Microsoft strongly recommends that developers creating Hosted Web Apps apply CSP on any page that will have access to UWP APIs, keeping your app and users safe and away from cross-site scripting harm.

Content URI rules and Scope

The web is full of hyperlinks that take us from one site to another without much thought. It’s actually one of the things that makes the web so great—it’s linkable!
Content URI rules are a part of Hosted Web Apps to provide additional security. They do this by limiting the “scope” of the web app. Only domains or URLs listed in the Content URI rules will be viewed within the Hosted Web App. Other linked pages will be seen as part of the web (and outside the app) and be opened in the default browser.

Building with Visual Studio

If you are using Visual Studio, you’ll set these rules in the manifest under a tab labeled “Content URIs.”

3_contentURIs

You can list a particular URL or a domain in this list, then set them to “include” to have them included in the app scope or “exclude” to have them considered out of scope. All URLs or domains not in the list are considered out of the application scope.

Building with command line tools

If you’re building your app with command line tools, use the “scope” attribute to set the application scope:



{  ...  
&quot;scope&quot;: &quot;https://app.mydomain.com/&quot;  
   ...  
}



The “scope” attribute is often good enough for most web apps, but if you find you need to list more than one domain or URL, then you’ll also want to include the ManifoldJS-specific “extended scope” to expand on what the W3C scope enables”:



{  
...  
&quot;scope&quot;: &quot;https://app.mydomain.com/&quot;,  
&quot;mjs_extended_scope:[                            
&quot;https://video.mydomain.com&quot;,                          &quot;https://music.mydomain.com&quot;                          
]  
...  
}



The Content URI rules are also used to determine the API access for each URI. For security reasons, you only want to enable Windows API access on pages that you trust.

There are two levels of API access you can provide. The first is “allow for web only,” which enables only APIs created by the addWebAllowedObject API. This access allows you to expose particular UWP or custom APIs into your Hosted Web App and does not give your URI access to the entire UWP API surface. The second option is “all,” which allows access to the entire UWP API surface, including APIs exposed through addWebAllowedObject.

Enabling access to these APIs in Visual Studio is again done through the Content URI rules. You simply set the level for each domain or URL.

4_setalevel

Your default value for each URI is “none.”

If you’re using ManifoldJS to build your app with the command line tool, you’ll do this via the API access value.



{
…
&quot;mjs_api_access&quot;: [  
{ &quot;match&quot;: &quot;https://app.mydomain.com/&quot;, &quot;access&quot;: &quot;allowForWebOnly&quot;, &quot;platform&quot;: &quot;windows10&quot; }
]
…
}



You can set multiple rules for different URIs. If you want to enable API access for everything in your scope, you can pass a wildcard to the value:



{
...
&quot;mjs_api_access&quot;: [  
{ &quot;match&quot;: &quot;*&quot; }
]
...
}



Keep in mind, ManifoldJS builds apps for all platforms, so the rules will apply to all platforms unless a specific platform is specified. You can read more about this topic on the wiki for ManifoldJS.

Maximizing security with Webviews and iframes

It’s a general rule of thumb to use an iframe when content is “known” and then to use a WebView for everything else. It’s important to remember that, in a Hosted Web App, you have access to an iframe at any time, as well as access to a WebView when you have enabled the UWP APIs on a page.

Remember that any URL loaded in an iframe must meet these two qualifications:

  1. URLs must be HTTPS
  2. URLs must be listed in Content URIs (application scope)

If a page doesn’t meet those qualifications, then it will not load in the iframe. This can be helpful in locking down content where you know what URLs should be loaded, and trust that if any other URL tries to load in your iframe, it will be rejected by the app.

Additionally, same-origin and window.postmessage() rules work just as they do in a browser. If your app is dealing with content that falls under the “unknown” category, then you’ll want to use a WebView to load this portion of content (keep in mind you can use a WebView inside the Hosted Web App).

By default, the WebView will have no access or knowledge of the parent page and will only have access to UWP APIs if they are enabled in the Content URIs for that specific domain or URL. However, you can still communicate back and forth between a WebView and the parent page through specified APIs, such as invokeScriptAsync and window.notify.

WebViews are generated in the DOM as an HTML tag:



&lt;x-ms-webview src=&quot;https://www.mydomain.com&quot;&gt;&lt;/x-ms-webview&gt;


The WebView can then be controlled like any other page element. It can be accessed via JavaScript and stylized via CSS.

Conclusion

A wise man once said “with great power comes great responsibility.” The same goes for Hosted Web Apps. With a Hosted Web App, your app can access UWP APIs from Bluetooth to users’ “contacts” and everything in between, and it is critical to keep your app secure. With Hosted Web Apps, you have every tool you need to do so.

Written by Jeff Burtoft (@boyofgreen), Principal Program Manager for TED Services & Devices, and Rami Sarieddine, Senior Tech Evangelist for Windows & Web

Building Hosted Web Apps with Windows App Studio

If you have a web app that’s currently available publicly via URL, you can easily bring it to Windows 10 using Windows App Studio’s Hosted Web App template. Windows App Studio is an online service that makes it easy to build an app for Windows with no coding required.  This blog post will walk you through how to create your own Hosted Web App.

With Windows App Studio, you create a native Windows 10 app in a browser by starting with a template or a blank canvas, then add information, data, services, and styling.  Once you’re finished, you generate the app as a Visual Studio solution, a sideloading package, or a publishing package that lets you reach the users of 200+ million Windows 10 devices in the Windows Store.

One of these templates is the Hosted Web App (HWA) template, which brings publicly accessible websites and web apps to Windows. It will ask you to enter the URL of your web app, add an app icon, enter settings, and get it ready to publish on the Windows Store. The process takes an absurdly short amount of time.

Things that take more time than building a Hosted Web App with Windows App Studio:

  • Checking the mail
  • Microwaving a bag of popcorn
  • Checking out at a grocery
  • Brushing your teeth (hopefully)
  • Watching an ad break during a TV show (perfect time for to make a HWA!)

So if you have 3 minutes to learn, let’s get started!

The process of creating a Hosted Web App using Windows App Studio can be broken down into four steps.

1_foursteps

Step One: Creating the project

If you haven’t already, sign up for Windows App Studio using your Microsoft account. It’s a completely free service. Once you’re signed up, navigate to the Start New Page, where you will see the option to create a Hosted Web App.

2_createyourHWA

Once you click Hosted Web App, a pop-out will appear. Enter the name you want to use for your Windows app and click Start with this one!  The device previews are simply to show approximately how the app might look on different screens.

3_nametheapp

Step Two: Configuring the app

Once you have created the project, you’ll be taken to the Content Editing screen. On this page you will enter the URL for the site you’re converting. And that’s all you really need to do.

4_themanifest

You then have the option to upload a Manifest, which is a JSON document containing information like application defaults and start-up parameters. You can also define additional URI rules and the rotation preference, but those are optional.

The preview on the right hand side of the screen shows what your Hosted Web App looks like on that type of device. If your preview doesn’t work, don’t worry. It usually just means the site doesn’t allow embedding in an iframe but should work when you generate the app.

After you enter in the URL and other information, you’re likely going to want to update the app’s icon from the default,  which is merely a placeholder. To do this, click the app icon on the navigation bar (to the right of the Content tab, highlighted below in green) to open the icon editor.

5_iconeditor

On the screen shown above, click the logo under the App logo heading (highlighted in purple above). That will open a file picker where you can select the icon you want to use. The tool will automatically generate the various icon sizes you need.

After you’ve done that, there is only one more configuration step. Click the Settings tab to edit your Store listing details such as your app’s description, language, Store association details, privacy policy, and other similar information. To publish to the Store, you must fill out the Store Association info here. For detailed instructions on publishing, please see the documentation.

6_publishtostore

Once you enter the information, click Save. Then you’re ready to finish and generate the app.

Step Three: Generating the app

When you’ve finished configuring settings, click the gray Finish button at the top. You’ll then be taken to a page where you can preview the app on different device form factors. The only thing you need to do on this page is click the big Generate button at the top. That will open a pop-out where you select the type of packages you want to generate. (The Visual Studio solution is always generated by default).

Note that in order to generate Publish packages, you’ll need to enter the Store Association details in the previous screen.

7_generatepublishpackages

After everything is ready to go, click Generate. It should take under a minute to run the generation. After that, you will have the app ready to go with the package type(s) you selected.

Conclusion

That’s everything you need to do to create a Hosted Web App in Windows App Studio.

We’d love to hear your feedback as you use the tool, so please let us know your thoughts on our User Voice and the Windows App Studio forums. Happy app building!

Hosted Web Apps: Go Beyond the App

We’ve talked about the right kind of app to start with for a Hosted Web App, and we’ve talked about why Hosted Web Apps are a good approach for a number of media partners. In this post, we’ll talk about how the app features and Windows APIs can be used to engage your users in new ways.

One of the difficulties of web apps is that when your users aren’t in the browser, there is no way to engage with them. There are a number of promising proposed standards, such as service workers and web notifications, but engaging users with a web app remains a challenge today. However, Hosted Web Apps offer a number of ways to accomplish this.

An advantage in moving to a Hosted Web App is the access that you have to native Windows features that allow you to reach out and pull the user back into your app experience. Let’s take a look at a few of these features now, but keep in mind there are lots more features to be used in a similar fashion.

Set Up Your App to Use Windows APIs

In order to access Windows APIs, you’ll need to expose the APIs for the pages from which you intend to call them. In short, you’ll want to declare it in your manifest. If you’re building the app from command line with ManifoldJS, then your manifest should include the following:



{
   &quot;mjs_api_access&quot;: [{ &quot;match&quot;: &quot;*://www.mysite.com/*&quot;, &quot;access&quot;: &quot;all&quot;, &quot;platform&quot;: &quot;windows10&quot; }]
}


If you’re building your app in Visual Studio, then you’ll want to add a corresponding Content URI rule:

1_URI

Understanding the Activation Object

When we talk about finding ways to engage users, we often run into conditions when the app is launched by a means other than clicking on the Start Menu tile. Some scenarios, like being launched from a background task, from a toast notification, or from Cortana, often need to take advantage of launch data to determine what to do once opened. This is what we call the “activation object,” which can be checked any time the app is launched.

Note: Windows APIs need to be exposed on this page for Windows object to exist. See above.

Here is a sample that listens for a app activation:



Windows.UI.WebUI.WebUIApplication.addEventListener('activated', function(args) {


  if (args.kind === Windows.ApplicationModel.Activation.ActivationKind.voiceCommand) {
      var results = args.result;
if (command === 'open') {

      details = results.semanticInterpretation.properties.section[0];
      switch (details) {
        case &quot;Cartoons&quot;:
          redirect = &quot;https://your.ownsite.com/categories/Cartoons&quot;;
          break;
        case &quot;Action&quot;:
          redirect = &quot;https://your.ownsite.com/categories/Action&quot;;
          break;
        case &quot;Drama&quot;:
          redirect = &quot;https://your.ownsite.com/categories/Drama&quot;;
          break;
       case &quot;Comedy&quot;:
          redirect = &quot;https://your.ownsite.com/categories/Comedy&quot;;
          break;
	default:
          redirect = &quot;https://your.ownsite.com/&quot;;
      }
      window.location.href = redirect;
		
	}

  }
  });


This “args” object contains all of the necessary information, such as the type of activation or, in the case of voice activation, the text used to activate the app and the command that it matches from the Voice Command Definition (VCD) file. You can read more about implementing the VCD and Cortana in a Hosted Web App in our previous post. The activation object can be useful to tell your Hosted Web App to navigate to one URL or another, and even pass data into the page.

Live Tiles

One of the unique features of Windows that allows you to draw a user back into your app is the use of Live Tiles. Live Tiles are a way to display data to a user on the Start menu (or Start screen) app tile.

Here’s a great example of the Fox News app displaying a live tile:

2_FoxNews

Live Tiles can be built from one of the many Live Tile Templates, or by creating your own template. In the following example, we’ll use a standard template and generate the Live Tile with some JavaScript on the page.

Step 1

Feature detection to make sure the user is running a Hosted Web App.



    if (typeof Windows !== 'undefined'&amp;&amp;
            typeof Windows.UI !== 'undefined' &amp;&amp;
            typeof Windows.UI.Notifications !== 'undefined') {
            //feature detect to run the code
        //your code goes inside this condition
       }


Step 2

Declare the namespace and set references: tile text (from template), image (from template), and tile template type.



   var notifications = Windows.UI.Notifications,
   tile = notifications.TileTemplateType.tileSquare150x150PeekImageAndText01,
   tileContent = notifications.TileUpdateManager.getTemplateContent(tile),
   tileText = tileContent.getElementsByTagName('text'), 
   tileImage = tileContent.getElementsByTagName('image'); 


Step 3

Set the tile content.



 tileText[0].appendChild(tileContent.createTextNode( 'Demo Message'));
        tileImage[0].setAttribute('src',  'https://unsplash.it/150/150/?random'); //pull random image
        tileImage[0].setAttribute('alt', 'Random demo image');


Step 4

Create the tile notification, which will update the Live Tile.



        var tileNotification = new notifications.TileNotification(tileContent);
        notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification);


The tile content may be the high score from a game or the latest news items, it all depends on your app. The tile will continue to cycle through the content even when the app has closed. View the entire code sample on GitHub.

Notifications

Notifications also use Windows APIs that can be called from JavaScript to activate. Like Live Tiles, notifications can be created from a template or built using your custom template. Our sample will start from one of the many templates you can choose from and will display a toast notification. We’ll break the code down into a few steps for clarity.

Step 1

Feature detection to make sure the user is running a Hosted Web App .



    if (typeof Windows !== 'undefined'&amp;&amp;
            typeof Windows.UI !== 'undefined' &amp;&amp;
            typeof Windows.UI.Notifications !== 'undefined') {
            //feature detect to run the code
        //your code goes inside this condition
       }


Step 2

Declare the namespace and set references: toast text (from template), toast image (from template), and tile template type.



   var notifications = Windows.UI.Notifications;
   var template = notifications.ToastTemplateType.toastImageAndText01;
   var toastXml = notifications.ToastNotificationManager.getTemplateContent(template);


Step 3

Set the toast notification content.



toastTextElements[0].appendChild(toastXml.createTextNode(&quot;This is the message for my toast&quot;));
    var toastImageElements = toastXml.getElementsByTagName(&quot;image&quot;);
    toastImageElements[0].setAttribute(&quot;src&quot;, &quot;https://unsplash.it/150/150/?random&quot;);
    toastImageElements[0].setAttribute(&quot;alt&quot;, &quot;random graphic&quot;);


Step 4

Create the toast notification and display it.



    var toast = new notifications.ToastNotification(toastXml);
    var toastNotifier = notifications.ToastNotificationManager.createToastNotifier();
    toastNotifier.show(toast);


The toast notification will display as soon as the “.show(toast)” is called. View the entire code sample on GitHub.
3_toastnotification

Running a Background task

Live Tiles and toast notifications are a great way to bring the user back into the app, especially when they are triggered by a push notification or from an event that runs in the background.

Hosted Web Apps, like any Universal Windows Platform app, have the ability to run background tasks scheduled by the system. The background task JavaScript code must live in the package, and it must be specified in the Manifest.

Whether you are using ManifoldJS from the command line, or you are building your app in Visual Studio, you’ll need to update the Windows app manifest (XML) to specify the file that contains the background task. In Visual Studio, the task can be added via the “Declarations” tab in the manifest. Choose background task, then specify your activity (systemEvent notification for this sample).

3_manifest

If you are updating the XML directly, you’ll add the following as a child of the “application” node:



      &lt;Extensions&gt;
        &lt;Extension Category=&quot;windows.backgroundTasks&quot; StartPage=&quot;js/background.js&quot;&gt;
          &lt;BackgroundTasks&gt;
            &lt;Task Type=&quot;systemEvent&quot; /&gt;
          &lt;/BackgroundTasks&gt;
        &lt;/Extension&gt;
      &lt;/Extensions&gt;


There are two parts to get a background task up and running. The first is to register the background task, which can be run from one of the JavaScript files on your site. You might be registering multiple background tasks in your app (e.g. push messages, system events) so it’s recommended to make a reusable registration function, like the following:



function RegisterBackgroundTask(taskEntryPoint, taskName, trigger, condition) {
    //
    // Check for existing registrations of this background task.
    //
    var taskRegistered = false;
    var background = Windows.ApplicationModel.Background;
    var iter = background.BackgroundTaskRegistration.allTasks.first();
    var hascur = iter.hasCurrent;

    while (hascur) {
        var cur = iter.current.value;

        if (cur.name === taskName) {
            taskRegistered = true;
            break;
        }
        hascur = iter.moveNext();
    }
    //
    // If the task is already registered, return the registration object.
    //
    if (taskRegistered == true) {

        return iter.current;
    }
    //
    // Register the background task.
    //
    var builder = new background.BackgroundTaskBuilder();
    builder.name = taskName;
    builder.taskEntryPoint = taskEntryPoint;
    builder.setTrigger(trigger);

    if (condition != null) {
        builder.addCondition(condition);
    }
    var task = builder.register();

    return task;
}


[/csharp]

This method will first check to make sure your task isn't already registered, as you don't want to pile on background tasks that will bog down your app and the system. If it doesn't find the task registered by name, it will then register it with the system. We'll initiate this registration function with a call like the following:

1


var systemTrigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);

RegisterBackgroundTask('jsbackground.js', 'mytestBGTask', systemTrigger, true)


We pass in the four required parameters:

  • background entry point (i.e. the JavaScript file)
  • task name
  • trigger that will fire the task
  • whether the request is active and not cancelled

The second part of the background task is what you actually want to run in the background. Once this system trigger fires, which in this case, is when the user changes time zones, the contents of background.js will be executed.

In our case, we can simply fire a notification to the user that they changed time zones or update a live tile showing the same. The Windows Dev Center has a number of detailed documents about both background tasks and background tasks from push notifications.

Interact with the world using NFC

Running your web app as a Hosted Web App gives you access to hardware APIs, such as Bluetooth and NFC that are inaccessible from the browser. These types of APIs allow you to interact with the world around you and can be added with just a few lines of code. They can also be combined with background tasks so your app doesn’t even need to be running to take advantage of them.

To access NFC in your web app, you’ll first need to enable this feature in the app manifest. This can be done through the capabilities tab of the manifest in Visual Studio, or by updating your manifest XML with the following:



  &lt;Capabilities&gt;
    &lt;Capability Name=&quot;internetClient&quot; /&gt;
    &lt;DeviceCapability Name=&quot;proximity&quot; /&gt;
  &lt;/Capabilities&gt;


You can then listen for the events, just like you do for DOM events, by setting up listeners. The first thing you’ll want to listen for is when the device comes in contact with NFC, and when it departs. There are events for both of these:



    var proximityDevice = Windows.Networking.Proximity.ProximityDevice.getDefault();

    if (proximityDevice != null) {
        proximityDevice.addEventListener(&quot;devicearrived&quot;, function (dataObj) {

            console.log('I have arrived at the device')

        }, false);
        proximityDevice.addEventListener(&quot;devicedeparted&quot;, function (dataObj) {

            console.log('i have departed from the device');

        }, false);
    }


When your device comes in contact with NFC, you’ll then have the opportunity to read the data from the NFC chip, or pull the ID from the chip and use it to establish a connection to the device via Bluetooth or Wi-Fi direct.

There are a number of great quick-start guides on the Windows Dev Center that walk you through the details. All of these can be used right from inside your Hosted Web App. Don’t forget you may also want to handle your NFC connection from background task.

Since your app might not always be running when the NFC chip is contacted, you can set up a custom protocol to launch your app. The NFC-connected chip will then launch the custom protocol for your app. To do this, update the manifest by adding a new declaration of protocol in your manifest. You can update your manifest XML file with the following:



            &lt;Extensions&gt;
        &lt;uap:Extension Category=&quot;windows.protocol&quot; StartPage=&quot;js/background.js&quot;&gt;
          &lt;uap:Protocol Name=&quot;nfcapptest&quot;&gt;
            &lt;uap:Logo&gt;imagesStoreLogo.png&lt;/uap:Logo&gt;
          &lt;/uap:Protocol&gt;
        &lt;/uap:Extension&gt;


In the scenario above, we’re having the protocol launch a background JavaScript file, but you can also have it launch your app directly. This will provide you with an activation object that can then be caught:



function onActivatedHandler(eventArgs) {
   if (eventArgs.detail.kind == Windows.ApplicationModel.Activation.ActivationKind.protocol) 
   {
       // TODO: Handle URI activation.

       // The received URI is eventArgs.detail.uri.rawUri
   }
}


You can then use the data passed in the activation object to navigate to a particular page in your Hosted Web App and even pass data into the page itself.

Conclusion

It’s a misconception that web apps have limited functionality and can’t handle complex features. With Hosted Web Apps, you have access to background tasks, notifications, and hardware like Bluetooth and NFC to build rich features into your app. Let these samples above inspire you to reach outside your app and engage more deeply with your users.

Written by Jeff Burtoft (@boyofgreen), Principal Program Manager for TED Services & Devices

Building a media-centric Hosted Web App

In our previous post, we kicked off our series on Hosted Web Apps (also known as Project Westminster) by publishing Building a Great Hosted Web App.  Today, we’ll show how an existing website that uses audio and video can use JavaScript code to integrate platform controls and functionality.

1_integration

Why cover media functionality?

By adding simple JavaScript code, media web apps can easily take advantage of Windows integrations in order to provide a richer experience to users than what is offered through the browser.

Hooking up the System Media Transport Controls

System Media Transport Controls (SMTC) are the common play, pause, back, and forward buttons exposed through Windows 10. When an app hooks into these controls, it will receive the events following user interaction. It will have the ability to handle them appropriately allowing users to accomplish actions such as skip to next track or pause the current video all from the OS.

2_buttons

Whether the app is using the <audio> or  <video> HTML element, the controls attribute needs to be added as follows:

.gist table { margin-bottom: 0; }

To handle the events from the System Media Transport , developers need to instantiate the controls by calling the proper Windows API in JavaScript. By doing feature detection for the Windows namespace to determine that the code is running in a Windows app it allows the same code to run error free in the browser.

.gist table { margin-bottom: 0; }

Once the DOM is loaded and the <audio> or <video> element is present, subscription to the pause, playing, and ended events is needed. Developers need to call the appropriate functions to update the state of the SMTC so it represents the media state change from the HTML element.

.gist table { margin-bottom: 0; }

Here are the definitions of the functions that need to be included in order to ensure correct SMTC state is reflected:

.gist table { margin-bottom: 0; }

Now, moving on to handling user interaction from the SMTC, developers need to ensure that the events raised by the SMTC when a user clicks or touches a button is reflected in the playing media.

.gist table { margin-bottom: 0; }

Here are the definitions of functions that are invoked in the sample once an event from the SMTC is fired in the app. These need to be implemented in order for the user-intended state change to be applied to the HTML element.

.gist table { margin-bottom: 0; }

By adding less than 100 lines of JavaScript code, a web app is able to cleanly integrate with OS functionality and give users more control through existing physical and UI style buttons.

For detailed information, check out this MSDN article on the SystemMediaTransportControls class.

Background Audio

No user wants their music to cut out when an app is minimized. By following a few easy steps, this can be avoided altogether on Windows desktop devices.

  1. Integrate with SMTC (covered above)
  2. Add the htmlmsAudioCategory=”BackgroundCapableMedia” to the html element

.gist table { margin-bottom: 0; }

  1. Add a background task in the manifest. This can be done through the manifest editor:

3_manifesteditor

Or directly in XML:

.gist table { margin-bottom: 0; }

On Windows mobile devices, the way to play audio in the background is through a separate, in-package background task. The background task has to be local, but it can be written in JavaScript. This allows the platform to keep the background task alive in a separate process from that of the app when the app is in the background. When the app enters in the background, it’s only the background task code that’s able to execute.

The sample shows how to enable background audio on a phone running Windows 10.

For more detailed information on how background audio functions on Windows, be sure to check out the Basics of Background Audio.

Going full screen

Full screen is a very common scenario for apps that support video playback. This functions differently in the browser versus in an app. In an app, developers have control over whether the video should take up the entire app window or the entire monitor when full screen is called. In order to take up the entire screen, developers must listen for the fullscreenchange DOM event. Once this event fires, a corresponding call to the WinRT API that puts the app in full screen needs to be made.

.gist table { margin-bottom: 0; }

This screen change handling logic calls the correct WinRT based on the fullscreenchange event:

.gist table { margin-bottom: 0; }

Listening for voice commands

Simple Cortana integration is easy to add as well. In this sample we show how a user can play a specific video through a voice command.

4_videoVCD

A Voice Command Definition (VCD) file needs to be added to the server so it can be accessed publicly. This VCD file is used to describe the commands that will be registered with the Windows Speech Platform and invoked when a user utters them to Cortana. Here’s the VCD file used in the sample:

.gist table { margin-bottom: 0; }

Adding the meta tag in the HTML page that’s set as the start page for the hosted web app will ensure the VCD file is downloaded and properly registered by the platform. This will be automatically handled when the web app is running in the app host with the meta tag present. The meta tag must include the location of the VCD file in the content attribute.

.gist table { margin-bottom: 0; }

Once the VCD file is created, added to the server, and the meta tag is included in HTML,  Cortana voice command activations need to be handled in JavaScript. Developers should always be feature detecting for the Windows namespace to avoid errors when the web app is running in the browser.

.gist table { margin-bottom: 0; }

By creating a Voice Command Definition File, adding the meta element in HTML, and event handling in JavaScript, the app is able to light up voice capabilities and add another dimension of user interaction. Not an overwhelming amount of code in order to integrate with Cortana.

Adding theme

A nice touch is to match the app title bar to the color or color theme of the app. The sample accomplishes this through a few lines of JavaScript code, enhancing the appearance of the app.

5_titlebar

Here is the code that needs to be added:

.gist table { margin-bottom: 0; }

Note: The code snippet shown above uses RGBA for the color values. Developers need to convert from Hex to RGBA if those are the color value types being used. A helper function can be found here.

For detailed information about the properties exposed through the titleBar, check out this MSDN article on the titleBar property.

Wrapping up

Adding these five easy Windows integrations to a media web app can make it more appealing to customers. There are many more platform features to integrate with so stay tuned and check back for more posts in the Hosted Web Apps series. The best part is, after the app is published to the Windows Store, developers can stick to their existing web workflow should they choose to add new integrations. Pushing new code updates will update the app without the need to re-submit to the Store.

Written by Kiril Seksenov, Engineer on the Web Platform Team

Additional resources