Extract URL data when URL contains #

Not applicable

Actually I'm trying to use G+ oAuth and the response code which i'm getting is bellow format:

<callback url>/#code=...

How could i parse that code in js

0 3 388
3 REPLIES 3

rmishra
Participant V

Are you trying to use Implicit Grant OAuth Workflow..and expecting to parse the fragment on the server side?

Not applicable

yeah you are right.They are sending authcode in url-fragment with callback URL

rmishra
Participant V

I am not sure if you are trying to write the javascript on the server or on the client.

You cannot read the query fragment on the server side . It's designed that way . The implicit flow is deemed more vulnerable than its counterparts, so an enhanced protection is to issue the code as a query fragment. This guarantees that the server does not see the URL fragment and it can be parsed only by a page/script on the domain which made the initial request

To parse it on the client side using Javascript(assuming it is executing in a browser)

var code = window.location.hash.substr(1) 

If there is only a code after the hash, the above code snippet will work AS IS. If there are more key-value params after the hash, you would iterate over them as follows

var fragmentParams = window.location.hash.substr(1)
var pairs = fragmentParams.split('&');
for(var i in pairs){
  var pair = pairs[i].split("=");
  //The pair can now be accessed as pair[0] and pair[1]
 }