Skip to content

Instantly share code, notes, and snippets.

@danielisaksson
Created November 13, 2014 16:20
Show Gist options
  • Save danielisaksson/f3a1afefdfaffdb4d22f to your computer and use it in GitHub Desktop.
Save danielisaksson/f3a1afefdfaffdb4d22f to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset='utf8'>
<title></title>
</head>
<body>
<script src='/_ah/channel/jsapi'></script>
<script>
var socket = null;
var hosts = [
'example.com',
'otherexample.com'
];
function connect(token, source, origin){
var channel = new goog.appengine.Channel(token);
var socket = channel.open();
socket.onopen = function(e){
send({type: 'open', data: e});
};
socket.onmessage = function(e){
send({type: 'message', data: e});
};
socket.onerror = function(e){
send({type: 'error', data: e});
};
socket.onclose = function(e){
send({type: 'close', data: e});
};
function send(msg){
if( source && origin ){
source.postMessage(msg, origin);
} else {
console.warn('bridge error: cannot send. no origin or source');
}
}
return socket;
}
function isValidOrigin(origin){
var protocol = location.protocol + '//';
for(var i=0; i<hosts.length; i++){
if( protocol + hosts[i] === origin ){
return true;
}
}
return false;
}
function onmessage(e){
if( !isValidOrigin(e.origin) ){
// ignore this since the window can receive messages from any frame
// (such as the app channel iframe)
} else if( e.data.token && !socket ){
socket = connect(e.data.token, e.source, e.origin);
} else if( socket && e.data == 'close' ){
// debug('close');
socket.close();
socket = null;
}
}
window.addEventListener('message', onmessage);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment