有办法“撤消”此脚本操作吗?

时间:2019-06-13 03:07:45

标签: javascript

我有一个脚本,可以通过Web浏览器打开移动手电筒,但是一旦打开,就无法将其关闭。因此,我想知道JavaScript是否有一种方法可以撤消先前的操作,或者可以终止先前执行的操作。

我从这里获得了代码: Is it possible to control the camera light on a phone via a website?

<script type="text/javascript">
//Test browser support
const SUPPORTS_MEDIA_DEVICES = 'mediaDevices' in navigator;

if (SUPPORTS_MEDIA_DEVICES) {
//Get the environment camera (usually the second one)
navigator.mediaDevices.enumerateDevices().then(devices => {

const cameras = devices.filter((device) => device.kind === 
'videoinput');

if (cameras.length === 0) {
  throw 'No camera found on this device.';
}
const camera = cameras[cameras.length - 1];

// Create stream and get video track
navigator.mediaDevices.getUserMedia({
  video: {
    deviceId: camera.deviceId,
    facingMode: ['user', 'environment'],
    height: {ideal: 1080},
    width: {ideal: 1920}
  }
}).then(stream => {
  const track = stream.getVideoTracks()[0];

  //Create image capture object and get camera capabilities
  const imageCapture = new ImageCapture(track)
  const photoCapabilities = 
imageCapture.getPhotoCapabilities().then(() => {

    //todo: check if camera has a torch

    //let there be light!
    const btn = document.querySelector('.switch');
    btn.addEventListener('click', function(){
      track.applyConstraints({
        advanced: [{torch: true}]
      });
    });
  });
});
});

//The light will be on as long the track exists


}

</script>
<button class="switch">Turn light on</button>

在打开手电筒时效果很好,但是在我的android设备上会保持打开状态。理想情况下,我还应该有一个开关来关闭脚本。

感谢大家的宝贵时间。

0 个答案:

没有答案