使用JavaScript怎么实现聊天接收到消息语言自动提醒功能

使用JavaScript怎么实现聊天接收到消息语言自动提醒功能

今天就跟大家聊聊有关使用JavaScript怎么实现聊天接收到消息语言自动提醒功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

思路

实时提醒

这个就比较明确了,就是在接收到消息的同时进行语音播放,大家可以根据自己的逻辑进行将代码放到合适的地方。

定时提醒

这个主要首先判断客户是否存在未读的消息,如果存在则语音提醒,如果不存在,则不进行提醒。故而要在HTML页面写一个定时器,每五分钟访问一次接口,查询客服是否存在未读消息,然后在后台开发一个接口用于返回客户是否存在未读消息。

代码实现

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>JS实现聊天接收到消息语言自动提醒(您有新的消息请注意查收)</title>
  <!--引入CSS、JS-->
  <script type="text/javascript" src="public/common/js/jquery-1.8.1.min.js"></script>
</head>
<style>
  #audio_click {
    margin-top: 32px;
    height: 40px;
  }
  #audio_click a {
    text-decoration: none;
    background: #2f435e;
    color: #f2f2f2;
    padding: 10px 30px 10px 30px;
    font-size: 16px;
    font-family: 微软雅黑, 宋体, Arial, Helvetica, Verdana, sans-serif;
    font-weight: bold;
    border-radius: 3px;
    -webkit-transition: all linear 0.30s;
    -moz-transition: all linear 0.30s;
    transition: all linear 0.30s;
  }
  #audio_click a:hover {
    background: #385f9e;
  }
</style>
<body>
<!--dom结构部分-->
<div >
  <!--用来存放item-->
  <h2>JS实现聊天接收到消息语言自动提醒</h2>
  <h4>(您有新的消息请注意查收)</h4>
  <div id="audio_click">
    <a id="btn_audio" href="#" rel="external nofollow" >播放语音</a>
  </div>
  <div id="audio_play"></div>
</div>
</body>
<script>
  $(function () {
    var html = '';
    html += '<audio id="audioPlay">';
    //格式ogg音频地址
    html += '<source src="/public/static/layui/newmsg.ogg" type="audio/ogg">';
    //格式mp3音频地址
    html += '<source src="/public/static/layui/newmsg.mp3" type="audio/mpeg">';
    //格式wav音频地址
    html += '<source src="/public/static/layui/newmsg.wav" type="audio/wav">';
    html += '</audio>';
    //将代码写入到页面中
    $(html).appendTo("#audio_play");
    //轮询ajax检测未读消息,每五分钟
    var setTime = setInterval(function () {
      $.ajax({
        type: "post",
        url: "{:url('index/getNoReadMsg')}", //查询客服是否有未读消息
        dataType: "json",
        success: function (ret) {
          if (ret.code == 1) {
            //有则进行播放语音提醒
            $('#audioPlay')[0].play();
          }
        }
      });
    }, 300000);
  });
  $("#btn_audio").click(function () {
    //这就代码就是播放语音的关键代码
    $('#audioPlay')[0].play();
  });
</script>
</html>

看完上述内容,你们对使用JavaScript怎么实现聊天接收到消息语言自动提醒功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。