问题
I have a Javascript Windows Store Application that hosts an iframe. The webpage inside of my iframe is not aware of my app, so it doesn't have any PostMessage
interface to my app.
The iframe will set a cookie when I 'log in' in the iframe. But in my app, I don't believe that there is a way that I can get the iframe cookie. Is this correct?
What if the web page knows about my application? (i.e. I can change the webpage in the iframe) Do I use PostMessage?
回答1:
You can use PostMessage that your main page will receive the message.
Here is working example in Win8 Developer Preview:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=1024, height=768" />
<title>WinWebApp1</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>
<script src="/winjs/js/ui.js"></script>
<!-- WinWebApp3 references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
<script type="text/javascript">
window.attachEvent("onmessage", receiveMessage);
function receiveMessage(e) {
if (e.origin == "http://www.scrumpt.com")
document.getElementById("target-element-id").innerHTML = e.data;
}
</script>
</head>
<body>
<iframe src="http://www.scrumpt.com/frametest2.html" style="display: block; width: 699px; height: 296.95px; left: -499px; top: 0px;"></iframe>
<div data-win-control="WinJS.UI.ViewBox" style="display: block; top: 50%;">
<div class="fixed-layout">
<div id="target-element-id">Click on Send Message above</div>
</div>
</div>
</body>
</html>
On the server (it is live at this moment on http://www.scrumpt.com/frametest2.html) you have:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function send() {
parent.postMessage('hello world', '*');
}
</script>
</head>
<body>
<a href="javascript:send()">Send message</a>
</body>
</html>
make sure that your div ("target-element-id") has the correct id when if you copy paste the code above. VS might change the id to "Div1" when pasting.
来源:https://stackoverflow.com/questions/8901272/windows-store-app-and-iframe-cookie