Last active
June 16, 2017 17:31
-
-
Save shangoyanyi/1c62ae29526e93319db0ffeb52b09454 to your computer and use it in GitHub Desktop.
React - do spotify oauth with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var React = require("react"); | |
module.exports = React.createClass({ | |
..., | |
// open new spotify oauth window | |
handleLoginRequest: function(){ | |
var url = 'https://accounts.spotify.com/authorize' + | |
'?client_id=' + this.props.clientId + | |
'&redirect_uri=' + encodeURIComponent(this.props.redirectUri) + | |
'&scope=' + encodeURIComponent(this.props.scope) + | |
'&response_type=token' + | |
'&state=' + encodeURIComponent(this.props.state); | |
var width = 450, | |
height = 730, | |
left = (screen.width / 2) - (width / 2), | |
top = (screen.height / 2) - (height / 2); | |
var w = window.open( | |
url, | |
'Spotify', | |
'menubar=no,location=no,resizable=no,scrollbars=no,status=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left | |
); | |
}, | |
// handling spotify oauth callback message | |
handleLoginRequestCallback: function(event){ | |
var hash = JSON.parse(event.data); | |
if (hash.type == 'access_token') { | |
console.log(hash.access_token); | |
//do things here | |
} | |
}, | |
// add event listener to spotify oauth callback message | |
componentDidMount: function(){ | |
window.addEventListener("message", this.handleLoginRequestCallback, false); | |
}, | |
render: function() { | |
... | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// create another html page to receive oauth callback、parsing query string and do postMessage to opener | |
(function() { | |
var hash = {}; | |
window.location.hash.replace(/^#\/?/, '').split('&').forEach(function(kv) { | |
var spl = kv.indexOf('='); | |
if (spl != -1) { | |
hash[kv.substring(0, spl)] = decodeURIComponent(kv.substring(spl+1)); | |
} | |
}); | |
console.log('initial hash', hash); | |
if (hash.access_token) { | |
window.opener.postMessage(JSON.stringify({ | |
type:'access_token', | |
access_token: hash.access_token, | |
expires_in: hash.expires_in || 0 | |
}), '*'); | |
window.close(); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does this method works on a mobile browser ?