capture-screen.uvue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <template>
  2. <view class="uni-container">
  3. <page-head :title="title"></page-head>
  4. <view class="uni-common-mt">
  5. <text class="uni-title">截屏状态:{{ captureStatus }}</text>
  6. <view style="flex-direction: row;">
  7. <text class="uni-title">是否允许截屏</text>
  8. <switch :checked="allowCapture" @change="(e: UniSwitchChangeEvent) => toggleCaptureScreen(e.detail.value)" />
  9. </view>
  10. <view class="uni-btn">
  11. <button @click="startCaptureListener" type="primary" class="uni-common-mt">开启截屏监听</button>
  12. <button @click="stopCaptureListener" class="uni-common-mt">关闭截屏监听</button>
  13. </view>
  14. </view>
  15. </view>
  16. </template>
  17. <script setup lang="uts">
  18. import { state, setAllowCapture } from '@/store/index.uts'
  19. const title = '截屏监听'
  20. const allowCapture = ref(state.allowCapture)
  21. const captureStatus = ref('未监听')
  22. const captureCallback = ref<((res: OnUserCaptureScreenCallbackResult) => void) | null>(null);
  23. const toggleCaptureScreen = (checked: boolean) => {
  24. uni.setUserCaptureScreen({
  25. enable: checked,
  26. success: (res: SetUserCaptureScreenSuccess) => {
  27. allowCapture.value = checked
  28. setAllowCapture(checked)
  29. console.log('设置截屏状态成功:', res)
  30. },
  31. fail: (err:IUniError) => {
  32. console.log('设置截屏状态失败:', err)
  33. }
  34. })
  35. }
  36. const startCaptureListener = () => {
  37. captureCallback.value = (res: OnUserCaptureScreenCallbackResult) => {
  38. captureStatus.value = '检测到截屏'
  39. console.log('检测到用户截屏',res)
  40. }
  41. uni.onUserCaptureScreen(captureCallback.value)
  42. captureStatus.value = '正在监听'
  43. console.log('开始监听截屏')
  44. }
  45. const stopCaptureListener = () => {
  46. if (captureCallback.value != null) {
  47. uni.offUserCaptureScreen(captureCallback.value)
  48. captureStatus.value = '未监听'
  49. console.log('停止监听截屏')
  50. }
  51. }
  52. // 页面卸载时清理监听
  53. onUnmounted(() => {
  54. stopCaptureListener()
  55. })
  56. </script>