async - Dave's Blog


Edge browser and JavaScript UWP app security model comparison

2018 Nov 29, 2:21

There are two main differences in terms of security between a JavaScript UWP app and the Edge browser:

Process Model

A JavaScript UWP app has one process (technically not true with background tasks and other edge cases but ignoring that for the moment) that runs in the corresponding appcontainer defined by the app's appx manifest. This one process is where edgehtml is loaded and is rendering HTML, talking to the network, and executing script. Specifically, the UWP main UI thread is the one where your script is running and calling into WinRT.

In the Edge browser there is a browser process running in the same appcontainer defined by its appx manifest, but there are also tab processes. These tab processes are running in restricted app containers that have fewer appx capabilities. The browser process has XAML loaded and coordinates between tabs and handles some (non-WinRT) brokering from the tab processes. The tab processes load edgehtml and that is where they render HTML, talk to the network and execute script.

There is no way to configure the JavaScript UWP app's process model but using WebViews you can approximate it. You can create out of process WebViews and to some extent configure their capabilities, although not to the same extent as the browser. The WebView processes in this case are similar to the browser's tab processes. See the MSWebViewProcess object for configuring out of process WebView creation. I also implemented out of proc WebView tabs in my JSBrowser fork.


The ApplicationContentUriRules (ACUR) section of the appx manifest lets an application define what URIs are considered app code. See a previous post for the list of ACUR effects.

Notably app code is able to access WinRT APIs. Because of this, DOM security restrictions are loosended to match what is possible with WinRT.

Privileged DOM APIs like geolocation, camera, mic etc require a user prompt in the browser before use. App code does not show the same browser prompt. There still may be an OS prompt – the same prompt that applies to any UWP app, but that’s usually per app not per origin.

App code also gets to use XMLHttpRequest or fetch to access cross origin content. Because UWP apps have separate state, cross origin here might not mean much to an attacker unless your app also has the user login to Facebook or some other interesting cross origin target.

PermalinkCommentsedge javascript security uwp web-security wwa

GoBack/GoForward in Win10 UWP WebView

2018 Oct 23, 9:18

The GoBack and GoForward methods on the UWP WebView (x-ms-webview in HTML, Windows.UI.Xaml.Controls.WebView in XAML, and Windows.Web.UI.Interop.WebViewControl in Win32) act the same as the Back and Forward buttons in the Edge browser. They don't necessarily change the top level document of the WebView. If inside the webview an iframe navigates then that navigation will be recorded in the forward/back history and the GoBack / GoForward call may result in navigating that iframe. This makes sense as an end user using the Edge browser since if I click a link to navigate one place and then hit Back I expect to sort of undo that most recent navigation regardless of if that navigation happened in an iframe or the top level document.

If that doesn't make sense for your application and you want to navigate forward or back ignoring iframe navigates, unfortunately there's no perfect workaround.

One workaround could be to try calling GoBack and then checking if a FrameNavigationStarting event fires or a NavigationStarting event fires. If a frame navigates then try calling GoBack again. There could be async races in this case since other navigates could come in and send you the wrong signal and interrupt your multi step GoBack operation.

You could also try keeping track of all top level document navigations and manually navigate back to the URIs you care about. However, GoBack and GoForward also restore some amount of user state (form fills etc) in addition to navigating. Manually calling navigate will not give this same behavior.

PermalinkCommentsuri uwp webview

Multiple Windows in Win10 JavaScript UWP apps

2018 Mar 10, 1:47

Win10 Changes

In Win8.1 JavaScript UWP apps we supported multiple windows using MSApp DOM APIs. In Win10 we use and window and a new MSApp API getViewId and the previous MSApp APIs are gone:

Win10 Win8.1
Create new window MSApp.createNewView
New window object window MSAppView
viewId MSApp.getViewId(window) MSAppView.viewId

WinRT viewId

We use and window for creating new windows, but then to interact with WinRT APIs we add the MSApp.getViewId API. It takes a window object as a parameter and returns a viewId number that can be used with the various Windows.UI.ViewManagement.ApplicationViewSwitcher APIs.

Delaying Visibility

Views in WinRT normally start hidden and the end developer uses something like TryShowAsStandaloneAsync to display the view once it is fully prepared. In the web world, shows a window immediately and the end user can watch as content is loaded and rendered. To have your new windows act like views in WinRT and not display immediately we have added a option. For example
let newWindow ="", null, "msHideView=yes");

Primary Window Differences

The primary window that is initially opened by the OS acts differently than the secondary windows that it opens:

Primary Secondary Allowed Disallowed
window.close Close app Close window
Navigation restrictions ACUR only No restrictions

The restriction on secondary windows such that they cannot open secondary windows could change in the future depending on feedback.

Same Origin Communication Restrictions

Lastly, there is a very difficult technical issue preventing us from properly supporting synchronous, same-origin, cross-window, script calls. That is, when you open a window that's same origin, script in one window is allowed to directly call functions in the other window and some of these calls will fail. postMessage calls work just fine and is the recommended way to do things if that's possible for you. Otherwise we continue to work on improving this.


MSApp.getHtmlPrintDocumentSourceAsync - JavaScript UWP app printing

2017 Oct 11, 5:49

The documentation for printing in JavaScript UWP apps is out of date as it all references MSApp.getHtmlPrintDocumentSource but that method has been replaced by MSApp.getHtmlPrintDocumentSourceAsync since WinPhone 8.1.


Previous to WinPhone 8.1 the WebView's HTML content ran on the UI thread of the app. This is troublesome for rendering arbitrary web content since in the extreme case the JavaScript of some arbitrary web page might just sit in a loop and never return control to your app's UI. With WinPhone 8.1 we added off thread WebView in which the WebView runs HTML content on a separate UI thread.

Off thread WebView required changing our MSApp.getHtmlPrintDocumentSource API which could no longer synchronously produce an HtmlPrintDocumentSource. With WebViews running on their own threads it may take some time for them to generate their print content for the HtmlPrintDocumentSource and we don't want to hang the app's UI thread in the interim. So the MSApp.getHtmlPrintDocumentSource API was replaced with MSApp.getHtmlPrintDocumentSourceAsync which returns a promise the resolved value of which is the eventual HtmlPrintDocumentSource.


However, the usage of the API is otherwise unchanged. So in sample code you see referencing MSApp.getHtmlPrintDocumentSource the sample code is still reasonable but you need to call MSApp.getHtmlPrintDocumentSourceAsync instead and wait for the promise to complete. For example the PrintManager docs has an example implementing a PrintTaskRequested event handler in a JavaScript UWP app.

    function onPrintTaskRequested(printEvent) {    
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {

Instead we need to obtain a deferral in the event handler so we can asynchronously wait for getHtmlPrintDocumentSourceAsync to complete:

    function onPrintTaskRequested(printEvent) {    
var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
const deferral = args.getDeferral();
MSApp.getHtmlPrintDocumentSourceAsync(document).then(htmlPrintDocumentSource => {
}, error => {
console.error("Error: " + error.message + " " + error.stack);
PermalinkCommentsjavascript MSApp printing programming uwp webview win10 windows

WinRT Toast from PowerShell

2016 Jun 15, 3:54

I've made a PowerShell script to show system toast notifications with WinRT and PowerShell. Along the way I learned several interesting things.

First off calling WinRT from PowerShell involves a strange syntax. If you want to use a class you write [-Class-,-Namespace-,ContentType=WindowsRuntime] first to tell PowerShell about the type. For example here I create a ToastNotification object:

$toast = New-Object Windows.UI.Notifications.ToastNotification -ArgumentList $xml;
And here I call the static method CreateToastNotifier on the ToastNotificationManager class:
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppUserModelId);
With this I can call WinRT methods and this is enough to show a toast but to handle the click requires a little more work.

To handle the user clicking on the toast I need to listen to the Activated event on the Toast object. However Register-ObjectEvent doesn't handle WinRT events. To work around this I created a .NET event wrapper class to turn the WinRT event into a .NET event that Register-ObjectEvent can handle. This is based on Keith Hill's blog post on calling WinRT async methods in PowerShell. With the event wrapper class I can run the following to subscribe to the event:

function WrapToastEvent {
param($target, $eventName);

Add-Type -Path (Join-Path $myPath "PoshWinRT.dll")
$wrapper = new-object "PoshWinRT.EventWrapper[Windows.UI.Notifications.ToastNotification,System.Object]";
$wrapper.Register($target, $eventName);

[void](Register-ObjectEvent -InputObject (WrapToastEvent $toast "Activated") -EventName FireEvent -Action {

To handle the Activated event I want to put focus back on the PowerShell window that created the toast. To do this I need to call the Win32 function SetForegroundWindow. Doing so from PowerShell is surprisingly easy. First you must tell PowerShell about the function:

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
Then to call:
[PInvoke]::SetForegroundWindow((Get-Process -id $myWindowPid).MainWindowHandle);

But figuring out the HWND to give to SetForegroundWindow isn't totally straight forward. Get-Process exposes a MainWindowHandle property but if you start a cmd.exe prompt and then run PowerShell inside of that, the PowerShell process has 0 for its MainWindowHandle property. We must follow up process parents until we find one with a MainWindowHandle:

$myWindowPid = $pid;
while ($myWindowPid -gt 0 -and (Get-Process -id $myWindowPid).MainWindowHandle -eq 0) {
$myWindowPid = (gwmi Win32_Process -filter "processid = $($myWindowPid)" | select ParentProcessId).ParentProcessId;
} c# powershell toast winrt

WinRT Launcher API in PowerShell

2016 Mar 31, 10:12
You can call WinRT APIs from PowerShell. Here's a short example using the WinRT Launcher API:
$uri = New-Object System.Uri ""
Note that like using WinRT in .NET, you use the System.Uri .NET class instead of the Windows.Foundation.Uri WinRT class which is not projected and under the covers the system will convert the System.Uri to a Windows.Foundation.Uri.

Retweet of GonzoHacker

2015 Jul 1, 5:22
The call is asynchronous - it's just that the surrounding code doesn't have anything better to do but wait for a response

ios - Capture image via captureStillImageAsynchronouslyFromConnection with no shutter sound - Stack Overflow

2014 May 24, 2:42

The best hack I’ve seen in a while. With no way to disable the shutter sound from the capture photo API, the developer creates the inverse waveform of the shutter sound and plays it at the same time to cancel out the shutter sound.

PermalinkCommentstechnical humor ios photo sound

Serializing JavaScript Promise Execution

2013 Aug 10, 3:07
Occasionally I have need to run a set of unrelated promises in series, for instance an object dealing with a WinRT camera API that can only execute one async operation at a time, or an object handling postMessage message events and must resolve associated async operations in the same order it received the requests. The solution is very simply to keep track of the last promise and when adding a new promise in serial add a continuation of the last promise to execute the new promise and point the last promise at the result. I encapsulate the simple solution in a simple constructor:

    function PromiseExecutionSerializer() {
var lastPromise = WinJS.Promise.wrap(); // Start with an empty fulfilled promise.

this.addPromiseForSerializedExecution = function(promiseFunction) {
lastPromise = lastPromise.then(function () {
// Don't call directly so next promise doesn't get previous result parameter.
return promiseFunction();

The only thing to watch out for is to ensure you don't pass the result of a previous promise onto a subsequent promise that is unrelated.
PermalinkCommentsasync javascript promise technical

Coding in Marble - Rico Mariani's Performance Tidbits - Site Home - MSDN Blogs

2012 Feb 6, 8:47

In short: excessive use of promises leads to a ton of short lived objects and resulting poorer pref.

PermalinkCommentsperf technical javascript promise async

XSL Transforms in JavaScript

2007 Oct 7, 4:12In a previous post I mentioned an xsltproc like js file I made. As noted in that post, on Windows you can write console script files in JavaScript, name them foo.js, and execute them from the command prompt. I later found that MSDN has an XSLT javascript sample which looks similar to mine, but I like mine better for the XSLT parameter support and having a non-ridiculous way of interpreting filenames. The code for my xsltproc.js follows. The script is very simple and demonstrates the ease with which you can manipulate these system objects and all it takes is opening up notepad.
var createNewXMLObj = function() {
   var result = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
   result.validateOnParse = false;
   result.async = false;
   return result;

var args = WScript.arguments;
var ofs = WScript.CreateObject("Scripting.FileSystemObject");

var xslParams = [];
var xmlStyle = null;
var xmlInput = null;
var inputFile = null;
var outputFile = null;
var error = false;

for (var idx = 0; idx < args.length && !error; ++idx)
   if (args.item(idx) == "-o") {
      if (idx + 1 < args.length) {
         outputFile = ofs.GetAbsolutePathName(args.item(idx + 1));
         error = true;
   else if (args.item(idx) == "--param" || args.item(idx) == "-param") {
      if (idx + 2 < args.length) {
         xslParams[args.item(idx + 1)] = args.item(idx + 2);
         idx += 2;
         error = true;
   else if (xmlStyle == null) {
      xmlStyle = createNewXMLObj();
   else if (xmlInput == null) {
      inputFile = ofs.GetAbsolutePathName(args.item(idx));
      xmlInput = createNewXMLObj();

if (xmlStyle == null || xmlInput == null || error) {
   WScript.Echo('Usage:\n\t"xsltproc" xsl-stylesheet input-file\n\t\t["-o" output-file] *["--param" name value]');
else {
   var xslt = new ActiveXObject("MSXML2.XSLTemplate.3.0");
   xslt.stylesheet = xmlStyle;
   var xslProc = xslt.createProcessor();
   xslProc.input = xmlInput;

   for (var keyVar in xslParams)
      xslProc.addParameter(keyVar, xslParams[keyVar]);


   if (outputFile == null)
   else {
      var xmlOutput = createNewXMLObj();
PermalinkCommentsjs xml jscript windows xslt technical xsltproc wscript xsl javascript

Retrieving Data Using Script

2006 Nov 27, 3:09This topic includes an example of how to write a script that obtains data through Microsoft Windows HTTP Services (WinHTTP) either synchronously or asynchronously. The concepts demonstrated in this example provide the basis for writing client or middle-tiPermalinkCommentsmsdn development programming reference microsoft http javascript script

About Asynchronous Pluggable Protocols

2006 Mar 28, 11:36PermalinkCommentswindows ie urlmon pluggable-protocols msdn microsoft uri programming
Older Entries Creative Commons License Some rights reserved.