Search code examples
windows-8windows-store-appswinjs

WinJS css file from local storage


Follow up to this question: apply downloaded CSS on windows 8 metroUI app

So, yes, Windows says "for security reasons, you cannot navigate to HTML you have downloaded to this location and you cannot run any executable or potentially executable code, such as script or CSS. It is intended for media such as images or videos and the like."

But I really, really want to use that css file from my local storage. Shouldn't I be able to use the execUnsafeLocalFunction method to bypass this restriction like this?:

MSApp.execUnsafeLocalFunction(function () {
    el["href"] = "ms-appdata:///local/style.css"
});

It still throws "An app can’t load remote web content in the local context." I also tried just reading the file with localFolder.getFileAsync and readText, but nothing seems to help. Is there really no way to work around this?


Solution

  • I think I found a way to get the CSS to load.

    I tested the code below by adding a css file that sets the body background to red in the local storage folder.

    The code reads the contents of the file, creates a style tag in the head and adds the content of the css file to the style.

    var url = new Windows.Foundation.Uri(filename);
    
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(function (file) {
        Windows.Storage.FileIO.readTextAsync(file).then(function(text) {
    
            var style = document.createElement("style");
            style.innerText = text;
            document.getElementsByTagName("head")[0].appendChild(style);
    
        });
    });