Test if html5 geolocation permission already has been granted

后端 未结 3 683
时光取名叫无心
时光取名叫无心 2021-01-02 23:22

Does anyone know if there is a way to test if prior html5 geolocation permission has been granted?

I try to make a script that does not request the geolocation unles

3条回答
  •  执念已碎
    2021-01-02 23:55

    Best you can do is to keep track of this yourself...

    // In chrome you can now do this    
    navigator.permissions.query({name: 'geolocation'}).then(function(PermissionStatus){
        console.log(PermissionStatus.state) // prompt, granted, denied
        // even listen for changes
        PermissionStatus.onchange = function(){
            console.log(this.state)
        }
    })
    

    fallback method:

    // initialization
    if( sessionStorage.getItem("geo_access") === null ){
        // just assume it is prompt
        sessionStorage.setItem("geo_access", "prompt");
    }
    
    function ask(){
        navigator.geolocation.getCurrentPosition(function(){
            sessionStorage.setItem("geo_access", "granted");
    
        }, function(err){
            if(err.code == 1){ // PERMISSION_DENIED
                sessionStorage.setItem("geo_access", "denied");
            }
            sessionStorage.setItem("geo_access", "prompt");
        });
    };
    
    // Then somewhere
    ask();
    

提交回复
热议问题