How to give javascript alert from web context(Iframe) in metro app.

安稳与你 提交于 2019-12-22 20:33:19

问题


In my metro app ..I am using iframe to load a web application - basically a form which contains some controls and finally user click on finish button and i want to show alert

i know in metro app. we can give the alert using "new Windows.UI.PopupMessage" to show the alert. but how can i do the same from the web context(Iframe).

i have a function (showalert();) in my default.js where i am using the "new Windows.UI.PopupMessage" to show messages. if i am trying to access this function from iframe page like "window.parent.showalert();". i get exception saying access denied.

Please someone reply to this as this is very critical for me.

thanks & regards Goutham


回答1:


You can use HTML 5's postMessage to communicate between contexts.

Below is an image of a simplistic example with the relevant code snippets following it; the Bing Maps trip optimizer example uses this same technique on a grander scale.

The main page (default.js), which is running in the local context, includes an IFRAME loaded in web context via the following markup (I left out the unchanged <head> element to save space):

<body onload="localContext.onLoad();">
   <p style="margin-top: 150px">This is default.html in the local context</p>

   <div style="background-color: azure; width: 300px">
       <iframe src="ms-appx-web:///webpage.html" />
   </div>
</body>

localContext is defined in default.js as

var localContext = {

    onLoad: function () {
        window.attachEvent("onmessage",
            function (msg) {
                if (msg.origin == "ms-appx-web://bfddc371-2040-4560-a61a-ec479ed996b0")
                    new Windows.UI.Popups.MessageDialog(msg.origin).showAsync().then();
            });
    }

};

and it defines an onLoad function for default.html that registers a listener to the onmessage event, and when that event fires a MessageDialog is shown (or you can take whatever action you want to do in the local context).

Note that the parameter to the message event callback (msg here) also includes a origin property that you can check to make sure you're only handling messages from expected senders.

The web page hosted in the IFRAME calls postMessage in the onclick event handler of a button (you'll probably want to pull the invocation a separate .js file versus in-line)

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        This is webpage.html loaded into an iFrame
        <button id="button" onclick="window.parent.postMessage('Hello from Web Context', '*');">Say Hello</button>
    </body>
</html>


来源:https://stackoverflow.com/questions/12827495/how-to-give-javascript-alert-from-web-contextiframe-in-metro-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!