如何检测Chrome中是否已授予麦克风权限 [英] How to detect if microphone permissions have been granted in chrome
问题描述
我想检测一下加载时是否已在我的网站上授予麦克风权限而不实际运行如下内容:
I would liked to detect whether or not microphone permissions have been granted on my site when it loads without actually running something like the following:
navigator.webkitGetUserMedia({audio: active},
function(){alert('worked')},
function(){alert('failed')});
是否有一个简单的API来检测用户是否已永久授予我的应用程序的麦克风访问权限(运行该应用程序)通过https)?
Is there a simple API to detect whether the user has permanently granted microphone access to my application (which runs over https)?
推荐答案
你可能希望它可以从权限api访问,但它不是:(
You could hope that it would be accessible from the permission api, but it isn't :(
也许在这个功能中,这可以像其他部分一样工作:
Perhaps in the feature this could work like the rest of this:
navigator.permissions.query(
// {name: 'video'} <-- doesn't work
// {name: 'audio'} <-- doesn't work
{name: 'geolocation'}
// {name: 'notifications'}
// {name: 'midi', sysex: false}
// {name: 'midi', sysex: true}
// {name: 'push', userVisibleOnly: true}
// {name: 'push'} // without userVisibleOnly isn't supported in chrome M45, yet
).then(function(permissionStatus){
console.log(permissionStatus.state); // granted, denied, prompt
permissionStatus.onchange = function(){
console.log("Permission changed to " + this.state);
}
})
我看到它的唯一方法可能的情况是,如果您在请求许可时使用localStorage中的键/值项目自行跟踪。
The only way i see it possible is if you keep track of this yourself with a key/value item in localStorage when you ask for permission.
不幸的是,它在更改时不会通知您
Unfortunately it doesn't notify you when it has been changed
// initialization
if( localStorage.getItem("voice_access") === null ){
// just assume it is prompt
localStorage.setItem("voice_access", "prompt");
}
// Then somewhere
navigator.getUserMedia({audio: true}, function(e){
// http://stackoverflow.com/q/15993581/1008999
//
// In chrome, If your app is running from SSL (https://),
// this permission will be persistent.
// That is, users won't have to grant/deny access every time.
localStorage.setItem("voice_access", "granted");
}, function(err){
if(err.name == "PermissionDismissedError"){
localStorage.setItem("voice_access", "prompt");
}
if(err.name == "PermissionDeniedError"){
localStorage.setItem("voice_access", "denied");
}
});
你可以加倍努力,建立一个好的使用上面代码的小包装器并扩展/替换权限api以处理更多枚举名称并创建广播 api告诉其他标签何时发生变化。但为什么要这么复杂......? localStorage不能100%受信任。它可以随时随地更改,无论是权限还是存储都已清除
You could go the extra mile and build a nice little wrapper with this code above and extend/replace the permission api to handle more enum names and create a broadcast api to tell the other tabs when it changes. but why make it so complicated...? The localStorage can't be 100% trusted. it can be changed anywhere any time both with permission and storage cleared
这篇关于如何检测Chrome中是否已授予麦克风权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!