DEV Community

Cover image for Screenshot Prevention, Scope Issues, Observer Problems, Dialog Closure, Object Field Check
kouwei qing
kouwei qing

Posted on

Screenshot Prevention, Scope Issues, Observer Problems, Dialog Closure, Object Field Check

[Daily HarmonyOS Next Knowledge] Screenshot Prevention, Scope Issues, Observer Problems, Dialog Closure, Object Field Check

1. How to Implement Screenshot Prevention in HarmonyOS?

Reference demo:

aboutToDisappear(): void {
  let windowClass: window.Window | undefined = undefined;
  window.getLastWindow(getContext(this)).then((win) => {
  this.window = win
})
window.getLastWindow(getContext(this), (err: BusinessError, data) => {
  const errCode: number = err.code;
  if (errCode) {
    console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err));
    return;
  }
  windowClass = data;
  console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
  setWindowPrivacyMode(windowClass, true)
});
}


export function setWindowPrivacyMode(windowClass: window.Window, isPrivacyMode: boolean) {
  windowClass.setWindowPrivacyMode(isPrivacyMode);
  console.info(`setWindowPrivacyMode 已执行`);
}
Enter fullscreen mode Exit fullscreen mode

2. HarmonyOS Scope Issues

When using CustomDialog, calling the current page's method after clicking "Confirm" prompts it as non-callable. Is this a scope issue?

This is a this binding issue. If using confirm: this.onConfirm in the custom dialog, this refers to the dialog itself. Since the dialog has no jumpToMainPage() method, it errors with "is not callable". Suggest rewriting as:

confirm:()=>{
  this.onConfirm()
}
Enter fullscreen mode Exit fullscreen mode

3. Can @Watch Observe Changes in @Consume-Decorated State Variables in HarmonyOS?

Reference demo:

@Component
struct CompD {
  @Consume @Watch('onChange') selectedDate: Date;

  onChange() {
    console.info("值改变了!!!")
  }

  build() {
    Column() {
      Button(`child increase the day by 1`)
        .onClick(() => {
          this.selectedDate.setDate(this.selectedDate.getDate() + 1)
        })
      Button('child update the new date')
        .margin(10)
        .onClick(() => {
          this.selectedDate = new Date('2023-09-09')
        })
      DatePicker({
        start: new Date('1970-1-1'),
        end: new Date('2100-1-1'),
        selected: this.selectedDate
      })
    }
  }
}

@Entry
@Component
struct CompA {
  @Provide selectedDate: Date = new Date('2021-08-08')

  build() {
    Column() {
      Button('parent increase the day by 1')
        .margin(10)
        .onClick(() => {
          this.selectedDate.setDate(this.selectedDate.getDate() + 1)
        })
      Button('parent update the new date')
        .margin(10)
        .onClick(() => {
          this.selectedDate = new Date('2023-07-07')
        })
      DatePicker({
        start: new Date('1970-1-1'),
        end: new Date('2100-1-1'),
        selected: this.selectedDate
      })
      CompD()
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

4. HarmonyOS Custom Dialog this.controller.close() Fails or Returns undefined

Reference demo:

@CustomDialog
struct CustomDialogExample {
  controller?: CustomDialogController
  cancel: () => void = () => {
  }
  confirm: () => void = () => {
  }

  build() {
    Column() {
      Text('可展示在主窗口外的弹窗')
        .fontSize(30)
        .height(100)
      Button('点我关闭弹窗')
        .onClick(() => {
          if (this.controller != undefined) {
            this.controller.close()
            console.log('关闭成功')
          } else {
            console.log('关闭失败')
          }
        })
        .margin(20)
    }
  }
}

@Entry
@Component
struct CustomDialogUser {
  dialogController: CustomDialogController | null = new CustomDialogController({
    builder: CustomDialogExample({
      cancel: () => {
        this.onCancel()
      },
      confirm: () => {
        this.onAccept()
      }
    }),
    cancel: this.existApp,
    autoCancel: true,
    alignment: DialogAlignment.Center,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    showInSubWindow: true,
    isModal: true,
    customStyle: false,
    cornerRadius: 10,
  })

  aboutToDisappear() {
    this.dialogController = null 
  }

  onCancel() {
    console.info('Callback when the first button is clicked')
  }

  onAccept() {
    console.info('Callback when the second button is clicked')
  }

  existApp() {
    console.info('Click the callback in the blank area')
  }

  build() {
    Column() {
      Button('click me')
        .onClick(() => {
          if (this.dialogController != null) {
            this.dialogController.open()
          }
        }).backgroundColor(0x317aff)
    }.width('100%').margin({ top: 5 })
  }
}
Enter fullscreen mode Exit fullscreen mode

5. How to Check if an Object Contains a Key in HarmonyOS?

To check if res (an object returned by an API) contains the key ad_4:

let jsonobject:Record<string,Object> = JSON.parse(JSON.stringify(res)) as Record<string,Object>;
Object.keys(jsonobject).forEach(key => {
  if (key !== undefined && key === 'ad_4'){
    let ob4: CarouselInfo1[] = res[key] as CarouselInfo1[];
    for (let index = 0; index < ob4.length; index++) {
      this.rechargeCarouseInfo.push(ob4[index])
    }
  }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)