Search code examples
javascripthtmlfirefoxgoogle-openid

Google sign-in button doesn't load in Firefox if parent element is hidden


I'm using Google Sign-In JavaScript client to dynamically create a G+ Login button. The code looks something like this:

<div id="googleSignInButton">
    <span class="g-signin"
        data-scope="openid email"
        data-clientid="{{flow.client_id}}"
        data-redirecturi="{{flow.redirect_uri}}"
        data-accesstype="offline"
        data-cookiepolicy="single_host_origin"
        data-callback="googleLoginCallback"
        data-approvalprompt="force">
    </span>
</div>

It works fine. But in one specific situation it doesn't load. When using firefox AND with it's parent element hidden (display:none), it doesn't show up at all when it's parent is shown.

Check jsfiddle for example (check the html comment):

https://jsfiddle.net/uh6cjt7a/3/


Solution

  • When running on Firefox, if the element is "invisible" when you load the google API, it will set the width and height properties to 1px directly in the element's style. It's impossible to change it via CSS.

    One solution is to explicitly initialize the API after you make the element visible. You can do it using the go method.

    <script >
      window.___gcfg = {
        lang: 'en-US',
        parsetags: 'explicit' //Configure to initialize explicitly
      };
    </script>
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    

    And them, in the javascript do this

    var $ = document.querySelector.bind(document);
    
    function showHide() {
    
      var login_panel = $("#login_panel");
      console.log(login_panel);
      var display = login_panel.style.display === "none" ? "block" : "none";
      login_panel.style.display = display;
      gapi.signin.go(login_panel); //Initialize the API after the element becomes visible.
    }
    

    Check this jsfiddle with a working example.