Skip to content

Instantly share code, notes, and snippets.

@wookiehangover
Last active December 17, 2015 12:29
Show Gist options
  • Save wookiehangover/5609977 to your computer and use it in GitHub Desktop.
Save wookiehangover/5609977 to your computer and use it in GitHub Desktop.
jQuery(function() {
window.addEventListener('message', function(event) {
if( window.user ){
event.source.postMessage(window.user, '*');
}
}, false);
});
{
authenticate: function(service){
var baseUrl = config.SERVER + 'auth/' + service;
var ref = window.open(baseUrl, '_blank', 'location=yes,transitionstyle=fliphorizontal');
var self = this;
var dfd = new $.Deferred();
ref.addEventListener('loadstart', function(loadEvent) {
if( loadEvent.url !== config.SERVER ){
return;
}
ref.close();
window.addEventListener('message', function(event){
self.set(event.data);
self.trigger('authenticated');
self.fetch();
dfd.resolve();
_.defer(function(){
$(iframe).remove();
});
});
var iframe = document.createElement('iframe');
iframe.src = config.SERVER;
$(iframe).appendTo('body').load(function(){
iframe.contentWindow.postMessage('authenticate', config.SERVER);
});
});
setTimeout(function(){
if( dfd.state() !== 'resolved' ){
dfd.reject();
}
}, 60e3);
return dfd.promise();
}
}
@wookiehangover
Copy link
Author

@talentedmrjones Ok so the url in config.SERVER is your server that's running the authentication. The iframe is what actually let's you pass the session to your phonegap app.

The "window" that's created with window.open doesn't have the postMessage API exposed through what cordova gives you, but it does share a cookie store with the webview, which lets you borrow it's session by loading the server url in an iframe.

Then, you just postMessage back to yourself and you're in. I'm about to upload a repo of this that has the server and client code as a working example, just finishing up the readme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment