vue在本地调用浏览器摄像头扫一扫功能遇到的坑

vue调用浏览器摄像头需要在https协议下面进行,原则在下面加上devServer:{https:true},

然后输入例如:https://10.120.19.123:8080/#/的网址即可访问,但是会提醒不是安全使用 https 出现 “您的连接不是私密连接” 的问题。大部分时候只要点击“高级”,然后选择依然继续就行了,但是也可能出现如下的情况:可参见:https://www.jianshu.com/p/5461b6ecb94f
这个时候你可能已经高兴可以正常访问地址了,但是很遗憾,在登陆接口请求的时候却报错接口跨域,没法正常请求接口。
于是放弃了

------------------------以上可以跳过,仅代表实验思想。撤回devServer:{https:true}的设置-----------------

https://blog.csdn.net/weixin_46045222/article/details/112766551这个真正解决了不在https的情况下也能正常打开摄像头权限。
即:在浏览器地址栏输入:chrome://flags/#unsafely-treat-insecure-origin-as-secure

就会出现页面【里面输入对应项目地址(需要用摄像头项目地址)】输入:http://10.120.19.123:8080/
这个时候再回到项目最初状态下:正常访问,再调用摄像头,浏览器就会询问打开摄像头了,完美解决!
再看看设置里面摄像头以及打开啦。如何实现扫码功能及样式,可见我上篇文章:https://www.cnblogs.com/Fancy1486450630/p/15711014.html


-------------------------------2022/4/14更新------------------------------

针对devServer:{https:true}来解决这扫码问题。我们继续来针对https来做一版:参考文档:https://blog.csdn.net/weixin_41856395/article/details/120597131?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1.pc_relevant_antiscanv2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~CTRLIST~Rate-1.pc_relevant_antiscanv2&utm_relevant_index=2

1:vue.config.js文件:
module.exports = {
	devServer: {
	        port: 8080,
	        https: true,
	       
	    },
};
2:安装npm install @zxing/library --save
3:需要在页面有点击扫码的地方:
<div @click="scanCode">点击扫码</div>
<div>扫码结果:{{codeText}}</div>
 scanCode(){
			 // this.isShow=true
			  console.log('浏览器信息', navigator.userAgent);
			   this.$router.push({
			     path: '/qrcode'
			   });
		 },
4:路由页面router.js配置
{
    name: 'qrcode',//扫码
    path: '/qrcode',
    component: () => import('./view/qrcode'),
    meta: {
      title: '扫码',
    },
  },
5:qrcode.vue页面封装如下:
<template>
  <div class="page-scan">
    <!--返回-->
    <van-nav-bar title="扫描二维码/条形码" fixed
      @click-left="clickIndexLeft()"
      class="scan-index-bar">
      <template #left>
        <van-icon name="arrow-left" size="18" color="#fff"/>
        <span style="color: #fff"> 取消 </span>
      </template>
    </van-nav-bar>
    <!-- 扫码区域 -->
    <video ref="video" id="video" class="scan-video" autoplay></video>
    <!-- 提示语 -->
    <div v-show="tipShow" class="scan-tip"> {{tipMsg}} </div>
  </div>
</template>
 
<script>
import { BrowserMultiFormatReader } from '@zxing/library';
import { Dialog, Notify } from 'vant';
 
  export default {
    name: 'scanCodePage',
    data() {
      return {
        loadingShow: false,
        codeReader: null,
        scanText: '',
        vin: null,
        tipMsg: '正在尝试识别....',
        tipShow: false
      }
    },
    created() {
      this.codeReader = new BrowserMultiFormatReader();
      this.openScan();
    },
    destroyed(){
      this.codeReader.reset();
    },
    watch: {
      '$route'(to, from) {
        if(to.path == '/scanCodePage'){
          this.codeReader = new BrowserMultiFormatReader();
          this.openScanTwo();
        }
      }
    },
    methods: {
      async openScan() {
        this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = '正在调用摄像头...';
          console.log('videoInputDevices', videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf('back') > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        }).catch(err => {
          this.tipShow = false;
          console.error(err);
        });
      },
      async openScanTwo() {
        this.codeReader = await new BrowserMultiFormatReader();
        this.codeReader.getVideoInputDevices().then((videoInputDevices) => {
          this.tipShow = true;
          this.tipMsg = '正在调用摄像头...';
          console.log('videoInputDevices', videoInputDevices);
          // 默认获取第一个摄像头设备id
          let firstDeviceId = videoInputDevices[0].deviceId;
          // 获取第一个摄像头设备的名称
          const videoInputDeviceslablestr = JSON.stringify(videoInputDevices[0].label);
          if (videoInputDevices.length > 1) {
            // 判断是否后置摄像头
            if (videoInputDeviceslablestr.indexOf('back') > -1) {
              firstDeviceId = videoInputDevices[0].deviceId;
            } else {
              firstDeviceId = videoInputDevices[1].deviceId;
            }
          }
          this.decodeFromInputVideoFunc(firstDeviceId);
        }).catch(err => {
          this.tipShow = false;
          console.error(err);
        });
      },
      decodeFromInputVideoFunc(firstDeviceId) {
        this.codeReader.reset(); // 重置
        this.scanText = '';
        this.codeReader.decodeFromInputVideoDeviceContinuously(firstDeviceId, 'video', (result, err) => {
          this.tipMsg = '正在尝试识别...';
          this.scanText = '';
          if (result) {
            console.log('扫描结果', result);
            this.scanText = result.text;
			localStorage.setItem('codeText',result.text)
			this.clickIndexLeft()
			return
            if (this.scanText) {
              this.tipShow = false;
              // 这部分接下去的代码根据需要,读者自行编写了
			  // this.$emit("ok", result.text)
              // this.$store.commit('app/SET_SCANTEXT', result.text);
              // console.log('已扫描的小票列表', this.$store.getters.scanTextArr);
            }
          }
          if (err && !(err)) {
            this.tipMsg = '识别失败';
            setTimeout(() => {
              this.tipShow = false;
            }, 2000)
            console.error(err);
          }
        });
      },
      clickIndexLeft(){  // 返回上一页
        this.codeReader = null;
        this.$router.back();
		this.$destroy();//这个报错我自行去掉了
      }
    }
  }
</script>
 
<style lang="less">
.scan-index-bar{
  background-image: linear-gradient( -45deg, #42a5ff ,#59cfff);
}
.van-nav-bar__title{
  color: #fff !important;
}
.scan-video{
  height: 80vh;
}
.scan-tip{
  width: 100vw;
  text-align: center;
  margin-bottom: 10vh;
  color: white;
  font-size: 5vw;
}
.page-scan{
  overflow-y: hidden;
  background-color: #363636;
}
</style>
posted @ 2021-12-22 14:47  FancyAnnaYL  阅读(3480)  评论(2编辑  收藏  举报