E T*_*E T 13 javascript google-chrome
我希望检测在加载时是否已在我的网站上授予麦克风权限,而不实际运行如下所示的内容:
navigator.webkitGetUserMedia({audio: active},
function(){alert('worked')},
function(){alert('failed')});
Run Code Online (Sandbox Code Playgroud)
是否有一个简单的API来检测用户是否已永久授予我的应用程序(通过https运行)的麦克风访问权限?
End*_*ess 12
你可能希望它可以从权限api访问,但它不是:(
也许在这个功能中,这可能会像其他部分一样工作:
navigator.permissions.query(
// { name: 'camera' }
{ name: 'microphone' }
// { 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);
}
})
Run Code Online (Sandbox Code Playgroud)
我认为可能的唯一方法是,当您请求许可时,您可以使用localStorage中的键/值项自行跟踪.
不幸的是,它在更改时不会通知您
// initialization
if( localStorage.getItem('microphone') === null ){
// just assume it is prompt
localStorage.setItem('microphone', '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')
}
})
Run Code Online (Sandbox Code Playgroud)
您可以加倍努力,使用上面的代码构建一个漂亮的小包装器,并扩展/替换权限api以处理更多枚举名称,并创建一个广播 API以告知其他标签何时更改.但为什么要这么复杂......?localStorage不能100%受信任.它可以随时随地更改,同时清除权限和存储空间
小智 1
您已经获得了用于检查权限的轮询方法。以下是来自 MDN 的一些信息: https: //developer.mozilla.org/en-US/docs/Web/API/Navigator.getUserMedia
还有更多: https: //developer.mozilla.org/en-US/docs/WebRTC
这是一个例子:
navigator.getMedia (
// constraints
{
video: true,
audio: true
},
// successCallback
function(localMediaStream) {
var video = document.querySelector('video');
video.src = window.URL.createObjectURL(localMediaStream);
video.onloadedmetadata = function(e) {
// Do something with the video here.
};
},
// errorCallback
function(err) {
console.log("The following error occured: " + err);
}
);
Run Code Online (Sandbox Code Playgroud)