3

I have implemented Google Picker in my website using javascript. But Whenever a button to initialize picker is pressed, it gets blocked by browser.

I have searched and tried few solutions here like:

  1. Adding client.js instead of api.js
  2. Setting 'immediate' = false;

But they are not working for me. Please help !

msanford
  • 11,803
  • 11
  • 66
  • 93
aaryan
  • 2,229
  • 2
  • 10
  • 15
  • Based from this [post](https://stackoverflow.com/questions/30125804/), you need to call [`gapi.auth.init`](https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit) which initializes the authorization feature. Call this when the client loads to prevent popup blockers from blocking the auth window on `gapi.auth.authorize` calls. Here's also an [example](https://gist.github.com/Daniel15/5994054) suggested by this [thread](https://groups.google.com/forum/#!topic/google-picker-api/gL_rUTgE-Tg) that does not get blocked by popup blocker. – abielita Sep 19 '17 at 16:23

1 Answers1

1

I have found a solution for this, if the popup is fired from click event then browsers will not block it, so the main idea is to initiate once and afterward trigger the picker creation directly by the click event.

To achieve this you can follow these steps:

  1. Use client instead of auth2
  2. Initialize client
  3. onckick event must trigger the gapi.auth2.getAuthInstance().signIn() once, afterward it must trigger google.picker.PickerBuilder()

For more information you can see my GooglePicker wrapper class - gist

Or:

    var GoogleAuth;
    var oathToken;
    gapi.load('client', function () {
    gapi.client.init({client_id: "MY_CLIENT_ID", scope: "MY_SCOPE"}).then(function () {
        GoogleAuth = gapi.auth2.getAuthInstance();
        });
    });


    function pick() {
        if (!oathToken) {
            GoogleAuth.signIn().then(function () {
                const user = this.GoogleAuth.currentUser.get();
                oathToken = user.getAuthResponse().access_token;
            });
        } else {
            const picker = new google.picker.PickerBuilder()
                .addView(google.picker.ViewId.DOCS)
                .setOAuthToken(oathToken)
                .setDeveloperKey("MY_DEVELOPER_KEY")
                .setCallback((data) => myCallBack(data)).build();

            picker.setVisible(true)
            }
    }

    function myCallBack(data) {
        if (data[google.picker.Response.ACTION] === google.picker.Action.PICKED) {
            const docs = data[google.picker.Response.DOCUMENTS];
            const url = docs[0][google.picker.Document.URL];
            const name = docs[0][google.picker.Document.NAME];

            console.log("Picked file's name: ", name);
            console.log("Picked file's url: ", url);
            // etc...
        }
    }
Mudafar
  • 11
  • 2