3

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?

1 Answer 1

3

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);

    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this is exactly the way to load CSS dynamically: append it to the document in the DOM. You can do a similar thing with in-package files by creating <link> elements in the document header. THe sam strategy also works to unload CSS--remove the <link> or <style> element in the DOM and the CSS is unloaded.
Thanks, getFileFromApplicationUriAsync did the trick! For some reason appending to the document didn't work, but replacing the cssText of a link element worked.
This does not work for me. The loaded styles are all invalid in the DOM explorer. body { background-color: white;} is displayed as wrongly formatted background-color:white: It seems that innerText does not handle \r\n in my CSS file correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.