百度小程序授權更好體驗


 

當我們點擊拒絕后,可能有些功能不能更好的使用,而且我們想授權時又找不到授權框了。

廢話不多說,直接上代碼!

auth.js

Page({
    data:{

    },
    onLoad:function(){
        this.getUserInfo();
    },
    getUserInfo:function(){
         var _this=this;
        swan.authorize({
            scope: 'scope.userInfo',
            success: res => {
                swan.showToast({
                    title: '授權成功'
                });
                console.log(res)
                swan.getUserInfo({
                    success: function (res) {
                        console.log(res)
                        let userInfo=res.userInfo
                        swan.setStorageSync('user', userInfo);
                        swan.reLaunch({
                            //此路徑為相對路徑;如需寫為絕對地址,則可寫為‘/example/xxx?key=valu’。
                            url: '../index/index'  
                        });
                    }
                });
            },
            fail: err => {
                swan.showToast({
                    title: '授權失敗'
                });
                swan.showModal({
                    title: '警告',
                    content: '您點擊了拒絕授權,將無法進入小程序,請授權之后再進入!!!',
                    showCancel: false,
                    confirmText: '返回授權',
                    success: function (res) {
                        console.log(res)
                        if (res.confirm) {
                            console.log('用戶點擊了“返回授權”')
                            swan.getSetting({
                                success: function (res) {
                                    console.log(res)
                                    console.log(res.authSetting['scope.userInfo']);
                                    if(res.authSetting['scope.userInfo']){
                                        _this.getUserInfo();
                                    }
                                }
                            });
                        }
                    }
                })
                // swan.openSetting({
                //     success: function (res) {
                //         console.log(res)
                //         console.log(res.authSetting['scope.userInfo']);
                //         // console.log(res.authSetting['scope.userLocation']);
                //         if(res.authSetting['scope.userInfo']){
                //             _this.getUserInfo();
                //         }
                //     }
                // });

                
            }
        });
    },
    onReady: () => {
       
    },

    onShow: () => {
        console.log('onShow');
    },

    onHide: () => {
        console.log('onHide');
    }
})

  如果點擊允許,則直接進入小程序首頁。

項目源碼:https://github.com/DreamS001/baidu_small-.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM