Facebook callback has started appending #_=_ hash underscore to the Return URL

Does anyone know why? What is the solution?

share|improve this question
31  
Any idea how facebook appends these characters? Facebook redirects to my handler where I then handle the redirection to the return url, yet the characters are still appended to the url. – Ben Foster Feb 22 '12 at 16:41
17  
2013, still happening on Chrome... – TTT Apr 5 '13 at 12:49
19  
2014, still faced with this junk tag – David Cumps Jan 17 '14 at 20:05
22  
2015, still getting issue. – Brent Jan 26 '15 at 12:59
32  
2016,welcome to 2016 , still appending :D – ImranNaqvi Jan 12 '16 at 14:58

16 Answers 16

via Facebook's Platform Updates:

Change in Session Redirect Behavior

This week, we started adding a fragment #____=____ to the redirect_uri when this field is left blank. Please ensure that your app can handle this behavior.

To prevent this, set the redirect_uri in your login url request like so: (using Facebook php-sdk)

$facebook->getLoginUrl(array('redirect_uri' => $_SERVER['SCRIPT_URI'],'scope' => 'user_about_me'));

UPDATE

The above is exactly as the documentation says to fix this. However, Facebook's documented solution does not work. Please consider leaving a comment on the Facebook Platform Updates blog post and follow this bug to get a better answer. Until then, add the following to your head tag to resolve this issue:

<script type="text/javascript">
    if (window.location.hash && window.location.hash == '#_=_') {
        window.location.hash = '';
    }
</script>

Or a more detailed alternative (thanks niftylettuce):

<script type="text/javascript">
    if (window.location.hash && window.location.hash == '#_=_') {
        if (window.history && history.pushState) {
            window.history.pushState("", document.title, window.location.pathname);
        } else {
            // Prevent scrolling by storing the page's current scroll offset
            var scroll = {
                top: document.body.scrollTop,
                left: document.body.scrollLeft
            };
            window.location.hash = '';
            // Restore the scroll offset, should be flicker free
            document.body.scrollTop = scroll.top;
            document.body.scrollLeft = scroll.left;
        }
    }
</script>
share|improve this answer
8  
what field is left blank? This is very cryptic – user210504 Sep 15 '11 at 5:53
63  
Ridiculous. They can't even get their own docs right – Brenden Oct 7 '11 at 23:39
1  
The UPDATE works. – lambinator May 15 '12 at 22:14
9  
@Ryan Update almost works for me, I still get a hash (/#) on the end. Not happy with FB. – LenPopLilly Jun 3 '12 at 17:00
3  
This solution will erase the hash: <script type="text/javascript"> var idx=window.location.toString().indexOf("#_=_"); if (idx>0) { window.location = window.location.toString().substring(0, idx); } </script> Just be sure this to be the first tag in the head element. – Gorgi Rankovski Nov 12 '12 at 16:33

TL;DR

if (window.location.hash == '#_=_'){
    history.replaceState 
        ? history.replaceState(null, null, window.location.href.split('#')[0])
        : window.location.hash = '';
}

Full version with step by step instructions

// Test for the ugliness.
if (window.location.hash == '#_=_'){

    // Check if the browser supports history.replaceState.
    if (history.replaceState) {

        // Keep the exact URL up to the hash.
        var cleanHref = window.location.href.split('#')[0];

        // Replace the URL in the address bar without messing with the back button.
        history.replaceState(null, null, cleanHref);

    } else {

        // Well, you're on an old browser, we can get rid of the _=_ but not the #.
        window.location.hash = '';

    }

}

Step by step:

  1. We'll only get into the code block if the fragment is #_=_.
  2. Check if the browser supports the HTML5 window.replaceState method.
    1. Clean the URL by splitting on # and taking only the first part.
    2. Tell history to replace the current page state with the clean URL. This modifies the current history entry instead of creating a new one. What this means is the back and forward buttons will work just the way you want. ;-)
  3. If the browser does not support the awesome HTML 5 history methods then just clean up the URL as best you can by setting the hash to empty string. This is a poor fallback because it still leaves a trailing hash (example.com/#) and also it adds a history entry, so the back button will take you back to #_-_.

Learn more about history.replaceState.

Learn more about window.location.

share|improve this answer
4  
worked perfectly for me thankyou for taking the time to do this code, sincerely appreciate it – 422 Oct 10 '13 at 0:36
2  
Worked perfectly for me too. The other solution gets rid of any query parameters. – AdeelMufti Jan 10 '16 at 12:27
    
It does the same thing for google omniauth, so I get an error no route matches, it appends # (hashtag) after request uri https://.....herokua‌​pp.com/auth/google_oa‌​uth2/callback?s‌​tate=1‌​9feaacfe2342‌​3jh5jhhGS‌​DFwb41904‌​9ebb18dabdf8‌​&code=‌​4/glrY3-mSlTzwe‌​rwE‌​RTEG334eXcn3hOSxGu‌​‌​c51BAlglPa4AU# – Shalafister's Aug 17 '16 at 9:29
    
Worked for me better than the solution of @Ryan, as it does not delete the query. – olivmir Feb 23 at 9:43

if you want to remove the remaining "#" from the url

$(window).on('load', function(e){
  if (window.location.hash == '#_=_') {
    window.location.hash = ''; // for older browsers, leaves a # behind
    history.pushState('', document.title, window.location.pathname); // nice and clean
    e.preventDefault(); // no page reload
  }
})
share|improve this answer
2  
tried this. getting 'e is not defined' error in the console. – santosh Oct 15 '12 at 4:16
6  
$(window).on('load', function(e){ /*likebeats's code*/ } works. – ISHITOYA Kentaro Oct 24 '12 at 12:30
1  
i use this code by change e.preventDefault(); to event.preventDefault(); – printf Jul 2 '13 at 1:04
    
This code is assuming jQuery, and an onWindowReady event listener taking the argument e. – Jason Sperske Aug 18 '15 at 8:51

Not sure why they're doing this but, you could get around this by reseting the hash at the top of your page:

if (window.location.hash == "#_=_")
  window.location.hash = "";
share|improve this answer
2  
did not work for me – user210504 Sep 15 '11 at 6:26
    
doesn't work for me either... – bool.dev Mar 2 '12 at 22:13

Facebook uses a frame and inside of it everything functions using AJAX communication. The biggest problem in this case is preserving the current page state. As far I understand, Facebook decided to use simulated anchors. This means if you clicked somewhere, they simulate that as an anchor inside of your page, and when the AJAX communication starts, they change the anchor bit of your URL as well.

This solution helps you normally when you try to reload the page (not ENTER, press F5), because your browser sends the whole URL with anchors to the Facebook server. Therefore Facebook picks up the latest state (what you see) and you are then able to continue from there.

When the callback returns with #_=_ it means that the page was in its basic state prior to leaving it. Because this anchor is parsed by the browser, you need not worry about it.

share|improve this answer
1  
If you have a javascript framework like backbone or ember it is an issue as everything after the hash is interpreted by the router – Rudi Oct 24 '13 at 19:00
1  
URL fragment identifiers ("anchors") are not sent to the browser on a request. Also, this question is about OAuth, not about the main desktop site. The reason for this is OAuth security -- preventing attacks due to crafting a malicious redirect URI. – AndrewF Oct 27 '13 at 22:23

Major annoying, especially for apps that parse the URI and not just read the $_GET... Here's the hack I threw together... Enjoy!

<html xmlns:fb='http://www.facebook.com/2008/fbml'>
<head>
        <script type="text/javascript">
        // Get rid of the Facebook residue hash in the URI
        // Must be done in JS cuz hash only exists client-side
        // IE and Chrome version of the hack
        if (String(window.location.hash).substring(0,1) == "#") {
                window.location.hash = "";
                window.location.href=window.location.href.slice(0, -1);
                }
        // Firefox version of the hack
        if (String(location.hash).substring(0,1) == "#") {
                location.hash = "";
                location.href=location.href.substring(0,location.href.length-3);
                }
        </script>
</head>
<body>
URI should be clean
</body>
</html>
share|improve this answer
    
Be careful about making assumptions when parsing any data that you don't create. URI fragment identifiers were spec'd as early as RFC 1738 (in 1994) so if you use a correct URI parser, this should never be a problem. – AndrewF Oct 27 '13 at 22:28

You can also specify your own hash on the redirect_uri parameter for the Facebook callback, which might be helpful in certain circumstances e.g. /api/account/callback#home. When you are redirected back, it'll at least be a hash that corresponds to a known route if you are using backbone.js or similar (not sure about jquery mobile).

share|improve this answer

This was implemented by Facebook by design for security reasons. Here's the explanation from Eric Osgood, a Facebook Team member:

This has been marked as 'by design' because it prevents a potential security vulnerability.

Some browsers will append the hash fragment from a URL to the end of a new URL to which they have been redirected (if that new URL does not itself have a hash fragment).

For example if example1.com returns a redirect to example2.com, then a browser going to example1.com#abc will go to example2.com#abc, and the hash fragment content from example1.com would be accessible to a script on example2.com.

Since it is possible to have one auth flow redirect to another, it would be possible to have sensitive auth data from one app accessible to another.

This is mitigated by appending a new hash fragment to the redirect URL to prevent this browser behavior.

If the aesthetics, or client-side behavior, of the resulting URL are of concern, it would be possible to use window.location.hash (or even a server-side redirect of your own) to remove the offending characters.

Source: https://developers.facebook.com/bugs/318390728250352/

share|improve this answer
    
This is the only answer that actually explains why this happens, thanks, I think I'll leave the offending chars in my urls now that I know they're not an issue. – stephenmurdoch Mar 8 at 8:56

This can become kind of a serious issue if you're using a JS framework with hashbang (/#!/) URLs, e.g. Angular. Indeed, Angular will consider URLs with a non-hashbang fragment as invalid and throw an error :

Error: Invalid url "http://example.com/#_=_", missing hash prefix "#!".

If you're in such a case (and redirecting to your domain root), instead of doing :

window.location.hash = ''; // goes to /#, which is no better

Simply do :

window.location.hash = '!'; // goes to /#!, which allows Angular to take care of the rest
share|improve this answer
    
1.2+ , this works awesome. For 1.0 and below use window.location.hash = ''; – Pradeep Mahdevu Dec 23 '13 at 4:36
1  
Yes, I only tested this on 1.2, thanks for the specification ! – neemzy Dec 27 '13 at 15:08

I do not see how this problem is related to facebook AJAX. In fact the issue also occurs with JavaScript disabled and purely redirect based logins.

An example exchange with facebook:

1. GET <https://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&scope=email&redirect_uri=MY_REDIRECT_URL> RESPONSE 302 Found Location: <https://www.facebook.com/connect/uiserver.php?[...]>  
2. GET <https://www.facebook.com/connect/uiserver.php?[...]> RESPONSE 302 Found MY_REDIRECT_URL?code=FB_CODE#_  
3. GET MY_REDIRECT_URL?code=FB_CODE#_  

Happens only with Firefox for me too.

share|improve this answer

Adding this to my redirect page fixed the problem for me ...

if (window.location.href.indexOf('#_=_') > 0) {
    window.location = window.location.href.replace(/#.*/, '');
}
share|improve this answer
1  
this causes a window location change, initiating a page refresh – rpearce Jul 31 '13 at 15:31

With angular and angular ui router, you can fix this

    app.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {

      // Make a trailing slash optional for all routes
      // - Note: You'll need to specify all urls with a trailing slash if you use this method.
      $urlRouterProvider.rule(function ($injector, $location) {
        /***
        Angular misbehaves when the URL contains a "#_=_" hash.

        From Facebook:
          Change in Session Redirect Behavior
          This week, we started adding a fragment #_=_ to the redirect_uri when this field is left blank.
          Please ensure that your app can handle this behavior.

        Fix:
          http://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url#answer-7297873
        ***/
        if ($location.hash() === '_=_'){
          $location.hash(null);
        }

        var path = $location.url();

        // check to see if the path already has a slash where it should be
        if (path[path.length - 1] === '/' || path.indexOf('/?') > -1) {
          return;
        }
        else if (path.indexOf('?') > -1) {
          $location.replace().path(path.replace('?', '/?'));
        }
        else {
          $location.replace().path(path + '/');
        }
      });

      // etc ...
    });
});
share|improve this answer
    
doesn't work here - the route changes before the rule() is applied – Maël Nison Dec 21 '14 at 20:41

A change was introduced recently in how Facebook handles session redirects. See "Change in Session Redirect Behavior" in this week's Operation Developer Love blog post for the announcement.

share|improve this answer
1  
I am not sure, what is he referring to here – user210504 Sep 15 '11 at 6:26

For me, i make JavaScript redirection to another page to get rid of #_=_. The ideas below should work. :)

function redirect($url){
    echo "<script>window.location.href='{$url}?{$_SERVER["QUERY_STRING"]}'</script>";        
}
share|improve this answer
    
this is not a good idea I think because you are creating multiple useless requests – Prozi Jul 21 '16 at 21:00

A workaround that worked for me (using Backbone.js), was to add "#/" to the end of the redirect URL passed to Facebook. Facebook will keep the provided fragment, and not append its own "_=_".

Upon return, Backbone will remove the "#/" part. For AngularJS, appending "#!" to the return URL should work.

Note that the fragment identifier of the original URL is preserved on redirection (via HTTP status codes 300, 301, 302 and 303) by most browsers, unless the redirect URL also has a fragment identifier. This seems to be recommended behaviour.

If you use a handler script that redirects the user elsewhere, you can append "#" to the redirect URL here to replace the fragment identifier with an empty string.

share|improve this answer

Using Angular 2 (RC5) and hash-based routes, I do this:

const appRoutes: Routes = [
  ...
  {path: '_', redirectTo: '/facebookLoginSuccess'},
  ...
]

and

export const routing = RouterModule.forRoot(appRoutes, { useHash: true });

As far as I understand, the = character in the route is interpreted as part of optional route parameters definition (see https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters), so not involved in the route matching.

share|improve this answer

protected by Igy Jul 12 '12 at 9:31

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.