Как снова получить объект googleUser на другой странице html (отличается от той, которая использовалась для входа) - PullRequest
0 голосов
/ 09 января 2020

Итак, мне удалось включить вход / выход Google для моего сайта в файле html: navbar. html. Код для входа точно такой же, как у Google здесь .

    <!-- Google Sign In/Out -->
    <script src="https://apis.google.com/js/api:client.js"></script>
    <script>
      var googleUser = {};
      var startApp = function() {
        gapi.load("auth2", function() {
          // Retrieve the singleton for the GoogleAuth library and set up the client.
          auth2 = gapi.auth2.init({
            client_id:
              "******************************************************",
            cookiepolicy: "single_host_origin",
            // Request scopes in addition to 'profile' and 'email'
            //scope: 'additional_scope'
            prompt: "consent"
          });
          attachSignin(document.getElementById("google-btn"));
          // To check if a user is indeed signed out
          auth2.isSignedIn.listen(signinChanged);
        });
      };

      function attachSignin(element) {
        console.log(element.id);
        auth2.attachClickHandler(
          element,
          {},
          function(googleUser) {
            // document.getElementById(
            //   "user-name"
            // ).innerText = googleUser.getBasicProfile().getName();
            // document.getElementById(
            //   "user-img"
            // ).src = googleUser.getBasicProfile().getImageUrl();
          },
          function(error) {
            // Changed from alert to console log
            console.log(JSON.stringify(error, undefined, 2));
          }
        );
      }

      var signinChanged = function(val) {
        console.log("Signin state changed to ", val);
        if (val) {
          $(".sign-in-btn").css({ display: "none" });
          $(".profile-btn").css({ display: "inline-block" });
        } else {
          $(".sign-in-btn").css({ display: "inline-block" });
          $(".profile-btn").css({ display: "none" });
        }
      };
    </script>
    <script>
      startApp();
    </script>
    <script>
      function signOut() {
        var auth2 = gapi.auth2.getAuthInstance();
        auth2.signOut().then(function() {
          console.log("User signed out.");
        });
      }
    </script>

Теперь, когда пользователь вошел в систему и допустил, что он щелкает ссылку и переходит на другую страницу. У меня проблемы с получением объекта googleUser снова на этой другой странице. Это то, что я пытался сделать, но это, похоже, не работает:

    <!-- Google Sign In -->
    <script src="https://apis.google.com/js/api:client.js"></script>
    <!-- Set User Details -->
    <script>
      var auth2 = gapi.auth2.getAuthInstance();
      var googleUser = auth2.currentUser.get();
      document.getElementById(
        "user-name"
      ).innerText = googleUser.getBasicProfile().getName();
      document.getElementById(
        "user-img"
      ).src = googleUser.getBasicProfile().getImageUrl();
    </script>

Я не уверен, нужно ли мне снова инициализировать auth2 на другой странице html.

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