为Google登录调用data-onsuccess方法

calling data-onsuccess method for Google sign-in

本文关键字:data-onsuccess 方法 调用 登录 Google      更新时间:2023-09-26

我正在尝试将Google Sign In集成到我的web应用程序中。

我的页面有Google按钮:

ModalDialogue.cshtml:
<a class="google g-signin2" data-onsuccess="onSignIn">Sign up with Google+</a>

我想在js中触发这个方法:

ModalDialogue.js:
      function onSignIn(googleUser) {
        var profile = googleUser.getBasicProfile();
        console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
        console.log('Name: ' + profile.getName());
        console.log('Image URL: ' + profile.getImageUrl());
        console.log('Email: ' + profile.getEmail());
      }

我知道

a] JavaScript在页面的范围内,因为我的其他函数-用于打开和关闭对话框-都可以工作。

b]按钮是与谷歌通信,因为点击它打开"登录与谷歌"对话框-然后一旦完成-更改按钮为"登录"之后。

如何触发onSignIn方法?或者至少我如何确定onsuccess是否被触发?

哦。我的坏。我没有注意到我将方法包装在闭包中。

对于将来访问此页面的人,我必须将函数定义移到按钮标签上方。这似乎无关紧要,因为data-on - success只是一个字符串。不幸的是,它没有抛出任何错误消息。

<html lang="en">
  <head>
    <meta name="google-signin-scope" content="profile email">
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID.apps.googleusercontent.com">
    <script src="https://apis.google.com/js/platform.js" async defer></script>
  </head>
  <body>
    <div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
    <script>
      function onSignIn(googleUser) {
        // Useful data for your client-side scripts:
        var profile = googleUser.getBasicProfile();
        console.log("ID: " + profile.getId()); // Don't send this directly to your server!
        console.log('Full Name: ' + profile.getName());
        console.log('Given Name: ' + profile.getGivenName());
        console.log('Family Name: ' + profile.getFamilyName());
        console.log("Image URL: " + profile.getImageUrl());
        console.log("Email: " + profile.getEmail());
        // The ID token you need to pass to your backend:
        var id_token = googleUser.getAuthResponse().id_token;
        console.log("ID Token: " + id_token);
      }
    </script>
  </body>
</html>

for for info

在script标签中定义onSignIn函数,这将使其全局可用。

<script>
          function onSignIn(googleUser) {
            console.log("I am clicked");
            var profile = googleUser.getBasicProfile();
            console.log("ID: " + profile.getId());
            console.log("Name: " + profile.getName());
            console.log("Image URL: " + profile.getImageUrl());
            console.log("Email: " + profile.getEmail());
          }
</script>

检查你的函数是否全局可用,从控制台调用window.onSignIn()或onSignIn()。你应该能够调用onSignIn,如果它是全局的。

script标签可以放在body标签的底部(用React js测试),

<body>
....
<script>
...
</script></body>

也可以使用async或defer属性放在head中。

这将发挥它的魔力,然后,

<div className="g-signin2" data-onsuccess="onSignIn"></div>

好运。

在浏览器中启用第三方cookie