getUserMedia - what if user makes no choice?

假如想象 提交于 2019-12-11 08:18:57

问题


I've adapted a library to record MP3 audio via the user's microphone. If the user allows or rejects the microphone access request, I'm fine, but I note that MDN says this:

Note that it is possible for the returned promise to neither resolve nor reject, as the user is not required to make a choice.

But it doesn't seem to say what, if anything, I can do catch that "no choice made" action. If the user merely quits the dialog, or blurs out of it without making a choice, can I catch that and adjust my UI accordingly?

Here's my current code:

navigator.mediaDevices.getUserMedia({audio: true}).then(function(stream) {
    build_ui();
    startUserMedia(stream);
}).catch(function(e) { //<-- doesn't fire if no choice made
    cfg.no_device_callback && cfg.no_device_callback(e);
});

回答1:


You could implement a timeout on the promise you have.

For instance, you could extend the Promise object and prototype as follows:

Promise.wait = function (ms) {
    return new Promise(function (resolve) {
        setTimeout(resolve, ms);
    });
};

Promise.prototype.timeout = function(ms) {
    return Promise.race([
        this, 
        Promise.wait(ms).then(function () {
            throw new Error("time out");
        })
    ])
};

Once you have that, you can just chain in a .timeout(10000):

navigator.mediaDevices.getUserMedia({audio: true})
         .timeout(10000).then(function(stream) {
//       ^^^^^^^^^^^^^^^
    build_ui();
    startUserMedia(stream);
}).catch(function(e) { //<-- now also fires if no choice made within 10 secs
    cfg.no_device_callback && cfg.no_device_callback(e);
});



回答2:


Firefox (57) does not allow the user to dismiss the permissions dialog. This dialog will remain visible indefinitely until you make a choice:

Safari (11) does not allow the user to dismiss the dialog. On top of that it also locks the entire browser (including other tabs) and thus forces the user's hand to make a choice:

Chrome (62) allows the user to dismiss the dialog through the top right [x] button:

In this case the choice and actionis obvious so Chrome throws a non spec error named PermissionDismissedError but this error might be removed in Chrome 64 which attempts to move towards spec compliant errors (see this Chromium bug).

I've written more abut getUserMedia errors in this article.



来源:https://stackoverflow.com/questions/42176505/getusermedia-what-if-user-makes-no-choice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!