Wrapping the MSApp.execUnsafeLocalFunction

Microsoft’s MSApp.execUnsafeLocalFunction can be used to dynamically add potentially unsafe code to the DOM. If you want to use this function in a cross platform HTML 5 app, you might want to wrap the function like:

if ("undefined" === typeof Utilities)
{
    Utilities = {};
}

Utilities.executeUnsafe = function (func)
{
    if ("undefined" !== typeof MSApp)
    {
        MSApp.execUnsafeLocalFunction(function ()
        {
            func();
        });
    }
    else
    {
        func();
    }
};

Now you can call a potentially unsafe function, like:

Utilities.executeUnsafe(App.myFunction);

Where App.myFunction should be replaced by your function.

How to add dynamic html content with jQuery 2.0.0 to a Windows Store app.

If you directly append html to the DOM that contains HTLM 5 data attributes or event handlers, like the onclick event to a Windows store app, you might get the exception during runtime:

 

Unhandled exception at line 5, column 18611 in ms-appx://3bce315e-3d91-43e6-8149-06d6377f04a1/js/libraries/jquery-2.0.0.min.js

0x800c001c – JavaScript runtime error: Unable to add dynamic content. A script attempted to inject dynamic content, or elements previously modified dynamically, that might be unsafe. For example, using the innerHTML property to add script or malformed HTML will generate this exception. Use the toStaticHTML method to filter dynamic content, or explicitly create elements and attributes with a method such as createElement.  For more information, see http://go.microsoft.com/fwlink/?LinkID=247104.

 

This exception even crashes my Windows Store app, because it is not caught anywhere in the code.

 

In my case this was caused by the following code:

var content = "";
content += ' <ul data-val="users" onclick="console.log(\'Clicked on users list.\');"> ';
content += ' <li>User1</li> ';
content += ' </ul> ';

var container = $('#content');
container.empty();
container.append(content);

This can be fixed by using jQuery document fragments:

var ul = $('<ul>', { 'data-val': 'listOfNames', 'onclick': 'console.log("Clicked on users list.");' });
ul.append('<li>' + 'User1' + '</li>');

var container = $('#content');
container.empty();
container.append(ul);

 

For more information on globally killing this exception, without changing the code (not recommended), see

http://blog.jonathanchannon.com/2013/01/24/using-angularjsbackbonejs-in-windows-8-javascript-app/

It uses jQuery.isUnsafe = true; so all calls to .append and appendTo are wrapped with Microsoft’s MSApp.execUnsafeLocalFunction.