HarmonyOS鸿蒙Next实现单页面防截屏功能鸿蒙示例代码

HarmonyOS鸿蒙Next实现单页面防截屏功能鸿蒙示例代码

介绍

本示例基于原生能力,实现对单个页面设置为隐私模式,使其可以禁止截屏,录屏及分享屏幕等行为。

实现单页面防截屏功能源码链接

效果预览

图片名称

使用说明

实现思路

  1. onWindowStageCreate生命周期函数中获取windowClass对象并保存,在对应需要防截屏的页面获取对象并设置隐私模式:

    windowStage.getMainWindow((err: BusinessError, data) => {
      let errCode: number = err.code;
      if (errCode) {
        console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
        return;
      }
      const windowClass = data;
      console.info('Succeeded in obtaining the main window. Data: ' + JSON.stringify(data));
      AppStorage.setOrCreate("windowClass",windowClass)
    })
    
  2. 需要设置防截屏页面:

    [@State](/user/State) windowClass: window.Window | null | undefined = AppStorage.get('windowClass')
    aboutToAppear(): void {
        let isPrivacyMode: boolean = true
        if (this.windowClass) {
          this.windowClass.setWindowPrivacyMode(isPrivacyMode); // 设置防截屏录屏
        }
    }
    

更多关于HarmonyOS鸿蒙Next实现单页面防截屏功能鸿蒙示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next实现单页面防截屏功能鸿蒙示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中实现单页面防截屏功能,可以通过Window类的setSecure方法来实现。以下是一个简单的示例代码:

import window from '@ohos.window';

// 获取当前窗口
let windowClass = await window.getLastWindow(this.context);

// 设置窗口为安全模式,禁止截屏
windowClass.setSecure(true);

这段代码首先通过window.getLastWindow方法获取当前窗口对象,然后调用setSecure(true)方法,将窗口设置为安全模式,从而禁止截屏操作。需要注意的是,此功能仅适用于当前窗口,切换窗口后需要重新设置。

如果需要取消防截屏功能,可以将setSecure方法的参数设置为false

windowClass.setSecure(false);

以上代码适用于HarmonyOS鸿蒙Next版本,确保开发环境已正确配置相关API。

回到顶部