Javascript 未兑现的承诺
每当我在音频上调用play方法时,我都会得到未捕获(承诺中)Dom异常错误,这是一个屏幕截图, 这就是我所做的Javascript 未兑现的承诺,javascript,jquery,html,Javascript,Jquery,Html,每当我在音频上调用play方法时,我都会得到未捕获(承诺中)Dom异常错误,这是一个屏幕截图, 这就是我所做的 function NotificationComment(cat,place) { clearInterval(notify); var url = $("#notification").val(); var val = $("#" + cat).val(); $.get(url, {type: cat, prev: val}, function (data) {
function NotificationComment(cat,place) {
clearInterval(notify);
var url = $("#notification").val();
var val = $("#" + cat).val();
$.get(url, {type: cat, prev: val}, function (data) {
arrayData = JSON.parse(data);
$('#'+place).html(' ' + arrayData.count + ' ');
$("#"+cat).val(arrayData.count);
if(arrayData.sound==1) {
notify = setInterval(function () {
$("#audio")[0].play();
NotificationComment('G', 'commentNot');
}, 2000);
} else {
notify = setInterval(function () {
NotificationComment('G', 'commentNot');
}, 2000);
}
});
}
if($("#auth").val()==1) {
notify = setInterval(function () {
NotificationComment('G', 'commentNot');
}, 2000);
}
感谢感谢@patrick Hund,我最终找到了一个解决方案,能够理解大多数浏览器限制声音和视频的自动播放这一事实,这导致了一个承诺例外,我通过创建一个隐藏的按钮来解决这个问题,每当有新的通知进来时,我都会单击这个按钮。这是我的代码 Js
function NotificationComment(cat,place){
clearInterval(notify);
var url = $("#notification").val();
var val = $("#"+cat).val();
$.get(url,{type:cat,prev:val},function (data) {
arrayData = JSON.parse(data);
$('#'+place).html(' '+arrayData.count+' ');
$("#"+cat).val(arrayData.count);
if(arrayData.sound==1){
$("#player")[0].click();
notify = setInterval(function () {
NotificationComment('G','commentNot');
}, 2000);
}else{
notify = setInterval(function () {
NotificationComment('G','commentNot');
}, 2000);
}
});
}
if($("#auth").val()==1) {
notify = setInterval(function () {
NotificationComment('G','commentNot');
}, 2000);
}
HTML
<audio id="myAudio">
<source src="{{url('assets2/audio/definite.mp3')}}">
</audio>
<button id="player" onclick="play()">Play</button>
<script>
var x = document.getElementById('myAudio');
function play() {
x.play();
}
</script>
玩
var x=document.getElementById('myAudio');
函数播放(){
x、 play();
}
感谢各位这些也是可能的解决方案,请转到chrome用户并在那里激活自动播放设置或使用
audio=new Audio('audiosource');
audio.play();
在javascript中 将此
$(“#音频”)[0]包装起来
使用尝试/catch
查看您是否能从中获得有用的信息debugging@quirimmo我得到了与截图中相同的回答抱歉我只是看了你的代码。我认为问题在于get
方法。尝试链接一个.fail
方法,该方法将捕获HTTP GET请求中的错误。当我调用play时,GET方法工作正常。我收到错误我猜浏览器不允许自动播放声音,大多数浏览器都不允许。在play语句周围添加try/catch,查看异常的错误类型是否为NotAllowedError。看到了吧,我很惊讶绕过自动播放权限限制这么容易。确定你的技巧在所有目标浏览器中都有效吗