Read the original article:onBackPress becomes ineffective when the window pop-up is opened.
Problem Description
When the window pop-up is not closed, and the page is redirected, the side-swipe gesture to return cannot trigger the page's onBackPress to return to the page.
The code for the problem pop-up is as follows:
import { window } from '@kit.ArkUI';
export class NYWindowDialog {
private static windowDialog: NYWindowDialog;
private dialogWindow: window.Window | undefined = undefined;
private name: string = 'XX_WINDOW_DIALOG'
private dialogConfig?: window.Configuration;
private params: object = new Object();
private winBgColor: string = '#40000000'
static getInstance(): NYWindowDialog {
if (!NYWindowDialog.windowDialog) {
NYWindowDialog.windowDialog = new NYWindowDialog()
}
return NYWindowDialog.windowDialog;
}
setParams(param: object): void {
this.params = param
}
getParams(): object {
return this.params
}
showWindowDialog(callback?: () => void): void {
this.dialogConfig = { name: this.name, windowType: window.WindowType.TYPE_DIALOG }
if (this.dialogWindow) {
this.closeWindowDialog();
}
window.createWindow(this.dialogConfig, (string, newWindow: window.Window) => {
if (!newWindow) {
return
}
this.dialogWindow = newWindow;
newWindow.setWindowTouchable(true);
newWindow.setUIContent(this.params['page']).then(() => {
newWindow.setWindowBackgroundColor(this.winBgColor);
});
newWindow.showWindow(() => {
if (callback !== undefined) {
callback();
}
});
});
}
closeWindowDialog(callback?: () => void): void {
if (this.dialogWindow != null) {
this.dialogWindow.destroyWindow(() => {
if (callback !== undefined) {
callback();
}
});
}
}
setWindowBgColor(color: string): void {
this.winBgColor = color
}
}
Background Knowledge
@ohos.window (Window): The window provides some basic capabilities for managing windows, including creating, destroying, setting various properties of the current window, and managing and scheduling between windows. Set window properties through the Configuration interface:
- name: Window name.
- windowType: Window type.
- ctx: Current application context information. If not set, it defaults to empty. In the FA model, this parameter is not needed to create a sub-window, and using this parameter will result in an error. In the Stage model, this parameter must be used to create a floating window, modal window, or system window.
- displayId: Current physical screen id. If not set, it defaults to -1, and this parameter should be an integer.
- parentId: Parent window id. If not set, it defaults to -1, and this parameter should be an integer.
- decorEnabled: Whether to display window decorations, effective only when windowType is TYPE_DIALOG. true means display, false means not display. The default value of this parameter is false.
- title: When the decorEnabled property is set to true, the title content of the window. The title display area does not exceed the leftmost end of the system three-key area on the far right, and the exceeding part is represented by ellipsis. If not set, it defaults to an empty string.
Troubleshooting Process
From the GIF, it can be seen that after the window opens, although it cannot be swiped back, the click event can still return to the previous page.
- Consider whether to disable the swipe gesture function after opening a pop-up window. In the onBackPress lifecycle, returning true indicates that the page handles the return logic itself and does not perform page routing; returning false indicates using the default routing return logic, and the return value is handled as false. This lifecycle is triggered when the user clicks the back button, and it only takes effect for custom components decorated with @Entry.
- Consider the modal popup issue. A modal popup is a strong interactive form of popup that interrupts the user's current operation process and requires the user to respond before continuing other operations. This type of popup is usually used in scenarios where important information needs to be conveyed to the user or confirmation is required. Querying the window type of @ohos.window (window) shows that the windowType parameter in the Configuration interface has the following types:
- TYPE_APP: Indicates an application sub-window.
- TYPE_SYSTEM_ALERT: Indicates a system alert window.
- TYPE_FLOAT: Indicates a floating window.
- TYPE_DIALOG: Indicates a modal window. Among them: The TYPE_DIALOG modal window page design is displayed in a modal manner, which means it prevents interaction with other windows during display, so it does not support swipe operations.
Analysis Conclusion
The TYPE_DIALOG modal window used in the problem code does not support swipe-to-return operations. Other types of windows can be used.
Solution
Change the modal pop-up to another type of pop-up. The options are as follows:
Option 1: Implement the pop-up effect by creating a sub-window and achieve the swipe-to-return effect.
1- Modify the EntryAbility page configuration.
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
// ...
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.loadContent('pages/pageA', (err, data) => {
// Global usage
AppStorage.setOrCreate('windowStage', windowStage);
});
}
// ...
}
2- Homepage creates and calls sub-windows.
// pageA.ets
import window from '@ohos.window'
import { common, Context } from '@kit.AbilityKit'
import * as subWin from './subWindow'; // Import named route page (sub window)
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
@State windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage
@State context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('This is Page A')
.fontSize(20)
.margin({ bottom: 10 })
Button('Click to open the sub-window')
.onClick(() => {
this.windowStage.createSubWindow('mySubWindow', (err, windowClass) => {
try {
windowClass.loadContentByName(subWin.entryName, (err: BusinessError) => {
const errCode: number = err.code;
if (errCode) {
console.error(`Failed to load the content. Cause code: ${err.code}, message: ${err.message}`);
return;
}
console.info('Succeeded in loading the content.');
// Set the coordinates of the top-left corner of the sub-window
windowClass.moveWindowTo(0, 0)
// Display Subwindow
windowClass.showWindow();
// Set sub-window full-screen layout to avoid safe area.
windowClass.setWindowLayoutFullScreen(false);
});
} catch (exception) {
console.error(`Failed to load the content. Cause code: ${exception.code}, message: ${exception.message}`);
}
})
})
}
.backgroundColor(Color.Gray)
.width('100%')
.height('100%')
}
}
3- Customize sub-window layout.
// subWindow.ets
import { window } from '@kit.ArkUI';
export const entryName: string = 'subWindow';
class TmpClass {
count: number = 10
}
@Entry({ routeName: entryName })
@Component
struct subWindow {
@StorageProp('pageInfos') pageInfos: NavPathStack = new NavPathStack()
onBackPress(): boolean | void {
window.findWindow('mySubWindow').destroyWindow()
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('This is a child window')
.fontSize(20)
.margin({ bottom: 10 })
Button('Click to jump to Page BB')
.onClick(() => {
this.getUIContext().getRouter().pushUrl({
url: 'pages/PageB'
})
})
.margin({
bottom: 15
})
Button('Click to close the sub-window')
.onClick(() => {
window.findWindow('mySubWindow').destroyWindow()
})
}
.backgroundColor(Color.White)
.width('100%')
.height('100%')
}
}
4- Create a jump test page.
// page B.ets
import { window } from '@kit.ArkUI'
@Entry
@Component
struct pageB {
@State windowStage: window.WindowStage = AppStorage.get('windowStage') as window.WindowStage
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('This is Page B, please swipe left.')
.fontSize(20)
.margin({ bottom: 10 })
.fontColor(Color.White)
}
.backgroundColor(Color.Green)
.width('100%')
.height('100%')
}
}
The effect is as follows:
Solution 2: Create a custom component to implement a pop-up window and achieve the slide-to-return effect.
For detailed examples, refer to the document: Implementing page-level pop-up functionality.
It is important to note that when using Navigation/router for route transitions, some pop-ups may appear on the page, so a reasonable implementation method needs to be chosen.

Top comments (0)