简体   繁体   English

防止谷歌选择器弹出窗口被浏览器阻止

[英]Prevent Google picker popup from blocking by browser

I have implemented Google Picker in my website using javascript. 我已经使用javascript在我的网站上实现了Google Picker。 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 添加client.js而不是api.js
  2. Setting 'immediate' = false; 设置'immediate' = false;

But they are not working for me. 但他们不适合我。 Please help ! 请帮忙 !

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. 我找到了一个解决方案,如果弹出窗口是从click事件触发的,那么浏览器就不会阻止它,因此主要的想法是启动一次,然后通过click事件直接触发选择器创建。

To achieve this you can follow these steps: 为此,您可以按照以下步骤操作:

  1. Use client instead of auth2 使用client而不是auth2
  2. Initialize client 初始化client
  3. onckick event must trigger the gapi.auth2.getAuthInstance().signIn() once, afterward it must trigger google.picker.PickerBuilder() onckick事件必须触发gapi.auth2.getAuthInstance().signIn()一次,之后必须触发google.picker.PickerBuilder()

For more information you can see my GooglePicker wrapper class - gist 有关详细信息,您可以查看我的GooglePicker包装类 - 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...
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM