首页 > 解决方案 > Uncaught In promise Dom 异常

问题描述

每当我在音频上调用 play 方法时,我都会收到 Uncaught (in promise) Dom Exception 错误,这是一个屏幕截图, 在此处输入图像描述

这就是我所做的

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);
}

谢谢

标签: javascriptjqueryhtml

解决方案


感谢@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>

多谢你们


推荐阅读