null - Dave's Blog


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.


JavaScript Types and WinRT Types

2016 Jan 21, 5:35

MSDN covers the topic of JavaScript and WinRT type conversions provided by Chakra (JavaScript Representation of Windows Runtime Types and Considerations when Using the Windows Runtime API), but for the questions I get about it I’ll try to lay out some specifics of that discussion more plainly. I’ve made a TL;DR JavaScript types and WinRT types summary table.

WinRT Conversion JavaScript
Struct ↔️ JavaScript object with matching property names
Class or interface instance JavaScript object with matching property names
Windows.Foundation.Collections.IPropertySet JavaScript object with arbitrary property names
Any DOM object

Chakra, the JavaScript engine powering the Edge browser and JavaScript Windows Store apps, does the work to project WinRT into JavaScript. It is responsible for, among other things, converting back and forth between JavaScript types and WinRT types. Some basics are intuitive, like a JavaScript string is converted back and forth with WinRT’s string representation. For other basic types check out the MSDN links at the top of the page. For structs, interface instances, class instances, and objects things are more complicated.

A struct, class instance, or interface instance in WinRT is projected into JavaScript as a JavaScript object with corresponding property names and values. This JavaScript object representation of a WinRT type can be passed into other WinRT APIs that take the same underlying type as a parameter. This JavaScript object is special in that Chakra keeps a reference to the underlying WinRT object and so it can be reused with other WinRT APIs.

However, if you start with plain JavaScript objects and want to interact with WinRT APIs that take non-basic WinRT types, your options are less plentiful. You can use a plain JavaScript object as a WinRT struct, so long as the property names on the JavaScript object match the WinRT struct’s. Chakra will implicitly create an instance of the WinRT struct for you when you call a WinRT method that takes that WinRT struct as a parameter and fill in the WinRT struct’s values with the values from the corresponding properties on your JavaScript object.

// C# WinRT component
public struct ExampleStruct
public string String;
public int Int;

public sealed class ExampleStructContainer
ExampleStruct value;
public void Set(ExampleStruct value)
this.value = value;

public ExampleStruct Get()
return this.value;

// JS code
var structContainer = new ExampleWinRTComponent.ExampleNamespace.ExampleStructContainer();
structContainer.set({ string: "abc", int: 123 });
console.log("structContainer.get(): " + JSON.stringify(structContainer.get()));
// structContainer.get(): {"string":"abc","int":123}

You cannot have a plain JavaScript object and use it as a WinRT class instance or WinRT interface instance. Chakra does not provide such a conversion even with ES6 classes.

You cannot take a JavaScript object with arbitrary property names that are unknown at compile time and don’t correspond to a specific WinRT struct and pass that into a WinRT method. If you need to do this, you have to write additional JavaScript code to explicitly convert your arbitrary JavaScript object into an array of property name and value pairs or something else that could be represented in WinRT.

However, the other direction you can do. An instance of a Windows.Foundation.Collections.IPropertySet implementation in WinRT is projected into JavaScript as a JavaScript object with property names and values corresponding to the key and value pairs in the IPropertySet. In this way you can project a WinRT object as a JavaScript object with arbitrary property names and types. But again, the reverse is not possible. Chakra will not convert an arbitrary JavaScript object into an IPropertySet.

// C# WinRT component
public sealed class PropertySetContainer
private Windows.Foundation.Collections.IPropertySet otherValue = null;

public Windows.Foundation.Collections.IPropertySet other
return otherValue;
otherValue = value;

public sealed class PropertySet : Windows.Foundation.Collections.IPropertySet
private IDictionary map = new Dictionary();

public PropertySet()
map.Add("abc", "def");
map.Add("ghi", "jkl");
map.Add("mno", "pqr");
// ... rest of PropertySet implementation is simple wrapper around the map member.

// JS code
var propertySet = new ExampleWinRTComponent.ExampleNamespace.PropertySet();
console.log("propertySet: " + JSON.stringify(propertySet));
// propertySet: {"abc":"def","ghi":"jkl","mno":"pqr"}

var propertySetContainer = new ExampleWinRTComponent.ExampleNamespace.PropertySetContainer();
propertySetContainer.other = propertySet;
console.log("propertySetContainer.other: " + JSON.stringify(propertySetContainer.other));
// propertySetContainer.other: {"abc":"def","ghi":"jkl","mno":"pqr"}

try {
propertySetContainer.other = { "123": "456", "789": "012" };
catch (e) {
console.error("Error setting propertySetContainer.other: " + e);
// Error setting propertySetContainer.other: TypeError: Type mismatch

There’s also no way to implicitly convert a DOM object into a WinRT type. If you want to write third party WinRT code that interacts with the DOM, you must do so indirectly and explicitly in JavaScript code that is interacting with your third party WinRT. You’ll have to extract the information you want from your DOM objects to pass into WinRT methods and similarly have to pass messages out from WinRT that say what actions the JavaScript should perform on the DOM.

PermalinkCommentschakra development javascript winrt

Retweet of waxpancake

2015 Feb 3, 8:12
Those magic, semi-private tweets I wrote about? Internally, Twitter calls them "nullcasted tweets." …

location.hash and are bad and they should feel bad

2014 May 22, 9:25
The DOM location interface exposes the HTML document's URI parsed into its properties. However, it is ancient and has problems that bug me but otherwise rarely show up in the real world. Complaining about mostly theoretical issues is why blogging exists, so here goes:
  • The location object's search, hash, and protocol properties are all misnomers that lead to confusion about the correct terms:
    • The 'search' property returns the URI's query property. The query property isn't limited to containing search terms.
    • The 'hash' property returns the URI's fragment property. This one is just named after its delimiter. It should be called the fragment.
    • The 'protocol' property returns the URI's scheme property. A URI's scheme isn't necessarily a protocol. The http URI scheme of course uses the HTTP protocol, but the https URI scheme is the HTTP protocol over SSL/TLS - there is no HTTPS protocol. Similarly for something like mailto - there is no mailto wire protocol.
  • The 'hash' and 'search' location properties both return null in the case that their corresponding URI property doesn't exist or if its the empty string. A URI with no query property and a URI with an empty string query property that are otherwise the same, are not equal URIs and are allowed by HTTP to return different content. Similarly for the fragment. Unless the specific URI scheme defines otherwise, an empty query or hash isn't the same as no query or hash.
But like complaining about the number of minutes in an hour none of this can ever change without huge compat issues on the web. Accordingly I can only give my thanks to Anne van Kesteren and the awesome work on the URL standard moving towards a more sane (but still working practically within the constraints of compat) location object and URI parsing in the browser.

Would an American Jury Even Convict Edward Snowden?

2013 Jul 16, 4:17
PermalinkCommentsnsa edward-snowden law legal

Subtleties of postMessage

2013 Jul 15, 1:00

In IE10 and other new browsers one may create MessageChannel objects that have two MessagePorts each connected (w3c spec calls it entangled) to one another such that postMessage on one port results in the message event firing on the other. You can pass an array of ports as the last parameter to postMessage and they show up in the ports property of the message event arg.


The postMessage here is like the worker postMessage and unlike the window and iframe postMessage in that it applies no origin checking:

  1. No origin postMessage in workers and MessagePorts: postMessage(messageData, ports)
  2. Origin postMessage in windows and iframes: postMessage(messageData, targetOrigin, ports)

Unfortunately the origin isn't an optional parameter at the end to make the two postMessages have the same signature.

On the event handler side, the event arg always has an origin property. But in the no origin case it is always the empty string.


There is also a source property on the message event arg which if set is an object that has a postMessage property allowing you to post back to your caller. It is set for the origin case, however, in the no origin case this property is null. This is somewhat reasonable because in the case of MessagePort and Workers there are only two endpoints so you always know the source of a message implicitly. Unlike the origin case in which any iframe or window can be calling postMessage on any other iframe or window and the caller is unknown. So not unreasonable but it would be nice if the source property was always set for consistency.

MessageChannel start

When a MessageChannel is created it has two MessagePorts, but until those ports are started they will queue up any messages they receive. Once started they will dispatch all queued messages. Ports don't have to be started to send messages.

A port may be started in two ways, either by explicitly calling the start method on the port, or by setting the onmessage callback property on the port. However, adding an event listener via addEventListener("message", does not start the port. It works this way in IE and Chrome and the spec states this as well.

The justification is that since you can have only one callback via onmessage that once set you must implicitly be ready to receive messages and its fine to start the port. As opposed to the addEventListener in which case the user agent cannot start implicitly because it doesn't know how many event listeners will be added.  I found Hixie stating this justification in geoloc meeting notes.


W3C Spec

Opera introduction

PermalinkCommentsDOM html javascript postMessage technical web-worker worker

Bug Spotting: Ctors with default parameters

2011 Dec 1, 4:59

The following code compiled just fine but did not at all act in the manner I expected:

BOOL CheckForThing(__in CObj *pObj, __in IFigMgr* pFigMgr, __in_opt LPCWSTR url)
BOOL fCheck = FALSE;
if (SubCheck(pObj))
I’m calling SubCheck which looks like:
bool SubCheck(const CObj& obj);

Did you spot the bug? As you can see I should be passing in *pObj not pObj since the method takes a const CObj& not a CObj*. But then why does it compile?

It works because CObj has a constructor with all but one param with default values and CObj is derived from IUnknown:

CObj(__in_opt IUnknown * pUnkOuter, __in_opt LPCWSTR pszUrl = NULL);
Accordingly C++ uses this constructor as an implicit conversion operator. So instead of passing in my CObj, I end up creating a new CObj on the stack passing in the CObj I wanted as the outer object which has a number of issues.

The lesson is unless you really want this behavior, don't make constructors with all but 1 or 0 default parameters. If you need to do that consider using the 'explicit' keyword on the constructor.

More info about forcing single argument constructors to be explicit is available on stack overflow.

PermalinkCommentsc++ technical bug programming

Bug Spotting: Smart pointers and parameter evaluation order

2011 Oct 19, 5:58
The following code works fine. I have a ccomptr named resolvedUri and I want to update its hostname so I do the following:
        CreateIUriBuilder(resolvedUri, 0, 0, &builder);
builder->CreateUri(0xFFFFFFFF, 0, 0, &resolvedUri);

But the following similar looking code has a bug:
    ResolveHost(resolvedUri, &resolvedUri);

The issue is that doing &resolvedUri gets the address of the pointer but also clears out the pointer due to the definition of my smart pointer class:
    operator T**()  
T *ptrValue = mPtrValue;
mPtrValue = NULL;
return &ptrValue;

In C++ there’s no guarantee about the order in which parameters for a function or method are evaluated. In the case above, &resolvedUri clears out the ccomptr before evaluating resolvedUri.Get() and so ResolveHostAlias gets a nullptr.

An interesting and related thread on stack overflow on undefined behavior in C++.
PermalinkCommentsc++ technical bug programming smart-pointer cpp

_opt Mnemonic

2011 May 24, 11:00

​I always have trouble remembering where the opt goes in SAL in the __deref_out case. The mnemonic is pretty simple: the _opt at the start of the SAL is for the pointer value at the start of the function. And the _opt at the end of the SAL is for the dereferenced pointer value at the end of the function.

SAL foo == nullptr allowed at function start? *foo == nullptr allowed at function end?
__deref_out void **foo No No
__deref_opt_out void **foo Yes No
__deref_out_opt void **foo No Yes
__deref_opt_out_opt void **foo Yes Yes
PermalinkCommentssal technical programming

IE9 Document Mode in WebOC

2011 Apr 4, 10:00

Working on GeolocMock it took me a bit to realize why my HTML could use the W3C Geolocation API in IE9 but not in my WebBrowser control in my .NET application. Eventually I realized that I was getting the wrong IE doc mode. Reading this old More IE8 Extensibility Improvements IE blog post from the IE blog I found the issue is that for app compat the WebOC picks older doc modes but an app hosting the WebOC can set a regkey to get different doc modes. The IE9 mode isn't listed in that article but I took a guess based on the values there and the decimal value 9999 gets my app IE9 mode. The following is the code I run in my application to set its regkey so that my app can get the IE9 doc mode and use the geolocation API.

        static private void UseIE9DocMode()
RegistryKey key = null;
key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION", true);
catch (Exception)
key = Registry.CurrentUser.CreateSubKey("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION");
key.SetValue(System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName, 9999, RegistryValueKind.DWord);
PermalinkCommentsweboc fck ie document mode technical ie9

A quote from Sacramento Credit Union

2010 May 14, 8:52It really is an actual quote from the Sacramento Credit Union's website: "The answers to your Security Questions are case sensitive and cannot contain special characters like an apostrophe, or the words “insert,” “delete,” “drop,” “update,” “null,” or “select.”"

Out of context that seems hilarious, but if you read the doc the next Q/A twists it like a defense in depth rather than a 'there-I-fixed-it'.PermalinkCommentstechnical security humor sql

5 Loading Web pages — HTML 5

2010 Apr 22, 10:26HTML5 has some notion of a 'null' origin. Not sure how this actually plays out though.PermalinkCommentsw3c site-of-origin null web browser application html html5 technical

Justin Frankel's blog

2009 Mar 10, 9:22Justin Frankel (Previously Winamp/Nullsoft guy) makes a designated graffiti box on his garage with the note: "All are welcome to express themselves in the box below. Printing within the above box is hereby expressly permitted and shall not be considered 'graffiti' in accordance with article #23 of the San Francico Municipal Code." Before graffiti: , And with graffiti:PermalinkCommentsgraffiti cultural-disobediance legal san-francisco nullsoft justin-frankel blog

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

Main Page - NSIS

2006 Dec 13, 10:47This is Nullsoft's free tool for generating installers. Its easy to use and does all of the things I want an installer to do.PermalinkCommentsnullsoft development installer install windows tool tools free programming script software

Encode-O-Matic Update

2006 Dec 3, 12:28I've updated Encode-O-Matic again. This is a tool I'm working on to convert between various Internet related encodings such as character sets, HTML encoding, URI encoding, base64, and IDN. In this update I've put it all into an installer. I'm using Nullsoft's installer generator to produce the installer. I've added a Base Conversion converter to convert between arbitrary bases and a Reverse converter that reverses the input by character, byte, or strings with arbitrary delimiters.PermalinkCommentsinstaller encodeomatic project charset nullsoft encoding
Older Entries Creative Commons License Some rights reserved.