As many of you know, DaniWeb now has an API.
It (optionally) uses OAuth 2.0 and it supports both server-side and client-side implementations.
The server-side method I have down pat. However, I had to hack together the clientside implementation, and although it works, I'm not sure it's done "correctly". I wasn't able to find any tutorials on the web about how you're supposed to do it. From what I could tell, every API simply included their own proprietary Javascript-based SDK.
Can any JS experts out there please take a look at my implementation and let me know how to streamline it a bit more? Specifically, in order to fetch an access token, I am calling window.open(), then checking to see if a window.opener exists, then passing the window's location into the window.opener's location, and then setting up a jQuery event listener to see if the URI for window.opener has changed. That doesn't seem quite right to me. I want to replace the whole process with some type of jQuery $.get() call in order to fetch the access token.
http://www.daniweb.com/api/demo/javascript
<h1>DaniWeb API Javascript Demo</h1>
<p id="hello-world"><a href="#" id="click-here" class="button cta-button">Connect to DaniWeb</a></p>
<pre><code></code></pre>
<script type="text/javascript">
<!--
var access_token;
$(function() {
if (window.opener != null && !window.opener.closed)
{
// Redirect the hash (which includes the access token) from the OAuth process
// to the main window and close the popup
opener.location.hash = window.location.hash;
window.close();
}
else
{
// Event listener for a hash change in the URI
$(window).on('hashchange', function() {
if (window.location.hash != '')
{
var string = window.location.hash.substr(1);
var query = string.split('&');
var param;
// Parse the URI hash to fetch the code
for (var i = 0; i < query.length; i++)
{
param = query[i].split('=');
if (param[0] == 'access_token')
{
access_token = param[1];
break;
}
}
if (access_token != '')
{
// Fetch ME!
$.getJSON('http://www.daniweb.com/api/me?access_token=' + access_token + '&callback=?', function(data) {
$('code').text($('div#source-code').html());
$('p#hello-world').html('<h1>Hi, ' + data.username + '! I know your username because I made a <a href="/api/documentation">JSONP request</a> with jQuery!</h1>');
});
}
}
});
}
});
$('#click-here').bind('click',function() {
var url = "http://www.daniweb.com/api/oauth/dialog?client_id=1&redirect_uri=http%3A%2F%2Fwww.daniweb.com%2Fapi%2Fdemo%2Fjavascript";
window.open(url, 'oauth', 'height=460,width=1180');
});
//-->
</script>