Перезагрузка приложения facebook в цикле, события входа в систему автоматически запускаются внутри window.fbAsyncInit - PullRequest
1 голос
/ 13 сентября 2011

Я занимаюсь разработкой приложения для Facebook (iframe).

Я добавил следующий код внизу моей страницы:

<script>
    window.fbAsyncInit = function() {

        FB.Canvas.setAutoResize();  

        FB.init({
            appId   : '<?php echo FACEBOOK_APP_ID; ?>',
            session : '<?php echo json_encode($session); ?>',
            status  : true,
            cookie  : true,
            xfbml   : true
        });

        // whenever the user logs in / out, we refresh the page
        FB.Event.subscribe('auth.login', function() {               
            window.location.reload();               
        });

        FB.Event.subscribe('auth.logout', function() {
            window.location.reload();
        });
    };

    (function() {
        var e = document.createElement('script');
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        e.async = true;
        document.getElementById('fb-root').appendChild(e);
    }());

</script>

Проблема здесь в том, что кажется, что события auth.login и auth.logout запускаются сразу внутри функции window.fbAsyncInit, даже если я не выхожу из (или не выхожу из системы) моего Facebook профиль.

Я не делаю таких действий, даже тогда эти события, похоже, запускаются, что заставляет их функции-обработчики перезагружать мое приложение (window.location.reload ();), и приложение переходит в бесконечный цикл перезагрузки.

Пожалуйста, ведите меня.

Спасибо

Ответы [ 2 ]

4 голосов
/ 02 января 2012

Из моего опыта вместо использования событий auth.logout и auth.login вы можете попробовать следующий код:

FB.Event.subscribe('auth.authResponseChange', function(response) {

  FB.getLoginStatus(function(response) {

    if (response.status === 'connected') {
      // the user is logged in and connected to your
      // app, and response.authResponse supplies
      // the user's ID, a valid access token, a signed
      // request, and the time the access token 
      // and signed request each expire
      var uid = response.authResponse.userID;
      var accessToken = response.authResponse.accessToken;

    } else if (response.status === 'not_authorized') {
      // the user is logged in to Facebook, 
      //but not connected to the app
    } else {
      // the user isn't even logged in to Facebook.
    }

  });

});
1 голос
/ 22 марта 2012

Я застрял, пытаясь решить эту ошибку в течение нескольких дней. Дело в том, что событие auth.login вызывается при загрузке SDK, даже если вы уже подключены, создавая бесконечный цикл. Я решил это, когда заставил код прослушивать событие authlogin и перезагружал страницу, только если пользователь не подключен.

<script type="text/javascript">
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '<?php echo AppInfo::appID(); ?>', // App ID
      channelUrl : '//<?php echo $_SERVER["HTTP_HOST"]; ?>/channel.html', // Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true // parse XFBML
    });

    // Listen to the auth.login which will be called when the user logs in
    // using the Login button
    FB.getLoginStatus(function(response) {
        console.log (response.status);
        //this is useful if you want to avoid the infinite loop bug
        //it only reloads page when you log in
        if (response.status != 'connected') {
            FB.Event.subscribe('auth.login', function(response) {
                // We want to reload the page now so PHP can read the cookie that the
                // Javascript SDK sat. But we don't want to use
                // window.location.reload() because if this is in a canvas there was a
                // post made to this page and a reload will trigger a message to the
                // user asking if they want to send data again.
                //window.location = window.location;
                //Im using the window.location.reload()
                window.location.reload();
            });
        }
    });
    FB.Canvas.setAutoGrow();
  };

  // Load the SDK Asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/all.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

</script>

Надеюсь, это работает!

Во всяком случае, это не единственная проблема, которая у меня есть. пожалуйста, проверьте этот пост и помогите мне, если можете невозможно прочитать переменные $ _SESSION в приложении PHP facebook

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...