Skip to content

Instantly share code, notes, and snippets.

@sohalloran
Created February 6, 2013 13:37
Show Gist options
  • Save sohalloran/4722536 to your computer and use it in GitHub Desktop.
Save sohalloran/4722536 to your computer and use it in GitHub Desktop.
postMessage() Example
// Client iframe container
<iframe id="xdwin" width="0px" height="0px" src="PROXY_SERVER/xd"></iframe>
<script>
window.addEventListener('message',function(event) {
if(event.origin !== ALLOWED_ORIGIN) return;
console.log(JSON.stringify(event.data));
},false);
function postMessage(e) {
var win = document.getElementById("xdwin").contentWindow;
win.postMessage("sid="+SID+"&path="
+encodeURIComponent(REST_RESOURCE),PROXY_SERVER);
}
</script>
// PROXY SERVER iframe page
<script>
window.addEventListener('message',function(event) {
console.log('message received: ' + event.data);
$.ajax({
cache: false,
dataType: 'json',
url: '/xdr?' + event.data,
success: function(data){
event.source.postMessage(JSON.stringify(data),event.origin);
}
});
},false);
</script>
// PROXY SERVER service
var xdHandler = function(req, res){
var sid = req.query["sid"];
var path = req.query["path"];
rest.get(path ,{
headers: {
'Accept':'application/json',
'Authorization': 'OAuth ' + sid,
'Content-Type': 'application/json',
}
}).on('complete', function(result) {
try {
res.json(result);
} catch(e) {
console.log(e);
}
res.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment