atelier:mitsuba

i love UI/UX, Blend, XAML, Behavior, P5, oF, Web, Tangible Bits and Physical computing. なにかあればお気軽にご連絡ください。atelier@c-mitsuba.com

その3:innerHTML:msWWA.execUnsafeLocalFunction

Windows 8 Developer Previewなので正式版とは異なる場合があります。
また、Windows Updateが走るときもあるため、エントリ執筆現在の情報をもとにかいています。

Metro Style AppでinnerHTMLをつかおうとすると、Runtime errorがでます。
ちょうどこんなコードです。


default.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WinWebApp5</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script src="/winjs/js/base.js"></script>
    <script src="/winjs/js/wwaapp.js"></script>
    <!-- WinWebApp5 references -->
    <link rel="stylesheet" href="/css/default.css" />
    <script src="/js/default.js"></script>
</head>
<body>
    <h1 id="title">title</h1>
    <button onmousedown="buttonClick()"></button>
</body>
</html>


default.js

function buttonClick() {
        document.getElementById("title").innerHTML = "hello metro";
}

Runtime Error

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 or the document.write method to add a script element will generate this exception. If the content is safe and from a trusted source, use a method to explicitly manipulate elements and attributes, such as createElement, or use msWWA.execUnsafeLocalFunction.

これを回避するには、createElementを使うか、msWWA.execUnsafeLocalFunctionを使えとあります。
これはinnerHTMLがTrustedで動作するコードなのが問題だそうです。
なので、JSを以下のように書き換えます。

function buttonClick() {
        msWWA.execUnsafeLocalFunction(function () {
        if (msWWA) {
            document.getElementById("title").innerHTML = "hello metro";
        }
    });
}

すると、エラーもなく実行することができます。
つまり、msWWA.execUnsafeLocalFunctionでくくったとこは、Unsafeだからね!な感じですかね。


ただ、時々書かなくても動いちゃうことがあったりエラーが出ないことがあるみたい。。
ほかのmsWWA.execUnsafeLocalFunctionを使ったプロジェクトがデバッグ中だと動いたり動かなったり、
一回このコードを書いたアプリを実行したら、他で全部うごいたりしました。。。
Developer Previewだから?
ここ要検証

ちなみに、msWWA.exeはTask ManagerのDetailから確認できます。

どうやらC:\Windows\System32\msWWA.exeが正体のようですね。
叩いてみると、XAML+CSで書いたMetroStyleAppのexeをたたいた時と同じようにAppContainerから叩いてね!なんて言われます。