From 42cc76c39ed6541ca5324e7f91be20ecdc03db62 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Fri, 20 Nov 2026 03:44:31 +0530 Subject: [PATCH 1/7] feat(h5): support hideHomeButton on H5 Taro.hideHomeButton was a temporarilyNotSupport stub on H5, although the H5 navigation bar rendered by @tarojs/router shows a "back to home" button when a page other than the home page is opened as the only page, just like mini programs do. Pages could therefore not hide that button. - @tarojs/router: add hideNavigationBarHomeButton, which triggers the __taroH5HideHomeButton event like the other navigation bar helpers. NavigationBarHandler records the hidden state in its per-page cache and setFnBtnState shows no button instead of the home button for that page. The cache entry is created on demand, because pages usually call the API in onShow, which runs before the navigation bar is loaded for the page, so the following load() does not show the button again. The back button and other pages are not affected. - @tarojs/taro-h5: implement hideHomeButton on top of the router helper. - types: mark hideHomeButton as supported on h5. Add router unit tests for hiding the button, hiding it before the page is loaded, keeping the back button and scoping the state to the page, and an H5 test for the API callbacks and the triggered event. --- .../taro-h5/__tests__/ui/navigation.test.ts | 23 +++++++ .../src/api/ui/navigation-bar/index.ts | 14 +++- .../__tests__/navigation-bar-test.ts | 64 +++++++++++++++++-- .../taro-router/src/router/navigation-bar.ts | 14 +++- packages/taro-router/src/utils/navigate.ts | 4 ++ .../taro/types/api/ui/navigation-bar.d.ts | 3 +- 6 files changed, 111 insertions(+), 11 deletions(-) diff --git a/packages/taro-h5/__tests__/ui/navigation.test.ts b/packages/taro-h5/__tests__/ui/navigation.test.ts index cac40c9ba0dc..9b9a0cef3c05 100644 --- a/packages/taro-h5/__tests__/ui/navigation.test.ts +++ b/packages/taro-h5/__tests__/ui/navigation.test.ts @@ -1,3 +1,4 @@ +import { eventCenter } from '@tarojs/runtime' import * as Taro from '@tarojs/taro-h5' import { buildApp } from '../utils' @@ -96,4 +97,26 @@ describe('navigation', () => { }) }) }) + describe('hideHomeButton', () => { + test('should ask the navigation bar to hide the home button', async () => { + const listener = jest.fn() + const success = jest.fn() + const fail = jest.fn() + const complete = jest.fn() + const expectRes = { errMsg: 'hideHomeButton:ok' } + eventCenter.on('__taroH5HideHomeButton', listener) + + try { + await expect(Taro.hideHomeButton({ success, fail, complete })).resolves.toEqual(expectRes) + await expect(Taro.hideHomeButton()).resolves.toEqual(expectRes) + } finally { + eventCenter.off('__taroH5HideHomeButton', listener) + } + + expect(listener).toHaveBeenCalledTimes(2) + expect(success.mock.calls).toEqual([[expectRes]]) + expect(complete.mock.calls).toEqual([[expectRes]]) + expect(fail).not.toHaveBeenCalled() + }) + }) }) diff --git a/packages/taro-h5/src/api/ui/navigation-bar/index.ts b/packages/taro-h5/src/api/ui/navigation-bar/index.ts index 51a28d0923a5..59eac8d8f63c 100644 --- a/packages/taro-h5/src/api/ui/navigation-bar/index.ts +++ b/packages/taro-h5/src/api/ui/navigation-bar/index.ts @@ -1,7 +1,7 @@ import Taro from '@tarojs/api' -import { setNavigationBarLoading, setNavigationBarStyle, setTitle } from '@tarojs/router' +import { hideNavigationBarHomeButton, setNavigationBarLoading, setNavigationBarStyle, setTitle } from '@tarojs/router' -import { getParameterError, shouldBeObject, temporarilyNotSupport } from '../../../utils' +import { getParameterError, shouldBeObject } from '../../../utils' import { MethodHandler } from '../../../utils/handler' // 导航栏 @@ -66,4 +66,12 @@ export function hideNavigationBarLoading (options: Taro.hideNavigationBarLoading return handle.success() } -export const hideHomeButton = /* @__PURE__ */ temporarilyNotSupport('hideHomeButton') +/** + * 隐藏当前页面导航栏中的返回首页按钮 + */ +export const hideHomeButton: typeof Taro.hideHomeButton = (options = {}) => { + const { success, fail, complete } = options + const handle = new MethodHandler({ name: 'hideHomeButton', success, fail, complete }) + hideNavigationBarHomeButton() + return handle.success() +} diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 40d1589ff767..5835f8c35fce 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -1,5 +1,6 @@ import NavigationBarHandler from '../src/router/navigation-bar' import stacks from '../src/router/stack' +import { hideNavigationBarHomeButton } from '../src/utils/navigate' import type { PageInstance } from '@tarojs/runtime' import type PageHandler from '../src/router/page' @@ -42,13 +43,13 @@ describe('NavigationBarHandler', () => { setStackSize(0) }) - describe('setFnBtnState', () => { - const getFnBtn = () => { - if (navigationBar.classList.contains('taro-navigation-bar-back-icon')) return 'back' - if (navigationBar.classList.contains('taro-navigation-bar-home-icon')) return 'home' - return 'none' - } + const getFnBtn = () => { + if (navigationBar.classList.contains('taro-navigation-bar-back-icon')) return 'back' + if (navigationBar.classList.contains('taro-navigation-bar-home-icon')) return 'home' + return 'none' + } + describe('setFnBtnState', () => { it.each([ ['the home page opened as the only page', HOME_PAGE, 1, 'none'], ['the home page navigated to from another page', HOME_PAGE, 2, 'back'], @@ -77,6 +78,57 @@ describe('NavigationBarHandler', () => { }) }) + describe('hideHomeButton', () => { + it('hides the home button of the current page', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + expect(getFnBtn()).toBe('home') + + hideNavigationBarHomeButton() + + expect(getFnBtn()).toBe('none') + }) + + it('keeps the home button hidden when called before the page is loaded', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + + // 页面在 onShow 中调用时,导航栏还未根据当前页面刷新 + hideNavigationBarHomeButton() + handler.load() + + expect(getFnBtn()).toBe('none') + }) + + it('does not hide the back button', () => { + setStackSize(2) + const handler = createHandler(OTHER_PAGE) + handler.load() + + hideNavigationBarHomeButton() + + expect(getFnBtn()).toBe('back') + }) + + it('only applies to the page that hid it', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideNavigationBarHomeButton() + expect(getFnBtn()).toBe('none') + + const anotherPage = '/pages/another/index' + Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) + handler.load() + expect(getFnBtn()).toBe('home') + + Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE }) + handler.load() + expect(getFnBtn()).toBe('none') + }) + }) + describe('setNavigationBarVisible', () => { const isVisible = () => { const show = navigationBar.classList.contains('taro-navigation-bar-show') diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index 21fcb4ae6825..a04848290146 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -12,6 +12,7 @@ interface NavigationBarCache { title?: string show?: boolean loading?: boolean + homeButtonHidden?: boolean } export default class NavigationBarHandler { @@ -38,6 +39,10 @@ export default class NavigationBarHandler { if (typeof frontColor === 'string') this.setNavigationBarTextStyle(frontColor) }) + + eventCenter.on('__taroH5HideHomeButton', () => { + this.hideHomeButton() + }) } private toHomeFn () { @@ -102,13 +107,20 @@ export default class NavigationBarHandler { this.fnBtnToggleToNone() } else if (stacks.length > 1) { this.fnBtnToggleToBack() - } else if (this.pageContext.homePage === currentRouter) { + } else if (this.pageContext.homePage === currentRouter || this.cache[this.pageContext.originPathname]?.homeButtonHidden) { this.fnBtnToggleToNone() } else { this.fnBtnToggleToHome() } } + hideHomeButton () { + // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,需要先初始化缓存,确保 load 时不会重新展示首页按钮 + this.setCacheValue() + this.cache[this.pageContext.originPathname].homeButtonHidden = true + this.setFnBtnState() + } + shiftLoadingState (show: boolean) { if (!this.loadingElement) return if (show) { diff --git a/packages/taro-router/src/utils/navigate.ts b/packages/taro-router/src/utils/navigate.ts index 851c75f83f31..7f365ad5ad6d 100644 --- a/packages/taro-router/src/utils/navigate.ts +++ b/packages/taro-router/src/utils/navigate.ts @@ -30,3 +30,7 @@ export function setNavigationBarStyle (option: { backgroundColor: string, frontC export function setNavigationBarLoading (loading: boolean): void { eventCenter.trigger('__taroH5setNavigationBarLoading', loading) } + +export function hideNavigationBarHomeButton (): void { + eventCenter.trigger('__taroH5HideHomeButton') +} diff --git a/packages/taro/types/api/ui/navigation-bar.d.ts b/packages/taro/types/api/ui/navigation-bar.d.ts index d978a3fe2642..b9a0658e7c87 100644 --- a/packages/taro/types/api/ui/navigation-bar.d.ts +++ b/packages/taro/types/api/ui/navigation-bar.d.ts @@ -122,7 +122,8 @@ declare module '../../index' { hideNavigationBarLoading(option?: hideNavigationBarLoading.Option): void /** 隐藏返回首页按钮。微信7.0.7版本起,当用户打开的小程序最底层页面是非首页时,默认展示“返回首页”按钮,开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏。 - * @supported weapp, tt, harmony + * @supported weapp, tt, h5, harmony + * @h5 隐藏当前页面 H5 导航栏中的返回首页按钮,不影响返回按钮 * @see https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.hideHomeButton.html */ hideHomeButton(option?: hideHomeButton.Option): Promise From 213c0917fb53b92a5f7091f92c19ede7823f66f8 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Sat, 21 Nov 2026 21:53:49 +0530 Subject: [PATCH 2/7] test(router): cover hidden home button after navigating away and back Also document that the hidden state is cached per route. --- .../__tests__/navigation-bar-test.ts | 18 ++++++++++++++++++ .../taro-router/src/router/navigation-bar.ts | 1 + 2 files changed, 19 insertions(+) diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 5835f8c35fce..702769c0bcb7 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -127,6 +127,24 @@ describe('NavigationBarHandler', () => { handler.load() expect(getFnBtn()).toBe('none') }) + + it('stays hidden after navigating to another page and back', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideNavigationBarHomeButton() + + const anotherPage = '/pages/another/index' + setStackSize(2) + Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) + handler.load() + expect(getFnBtn()).toBe('back') + + setStackSize(1) + Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE }) + handler.load() + expect(getFnBtn()).toBe('none') + }) }) describe('setNavigationBarVisible', () => { diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index a04848290146..a9ef539ccefd 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -116,6 +116,7 @@ export default class NavigationBarHandler { hideHomeButton () { // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,需要先初始化缓存,确保 load 时不会重新展示首页按钮 + // 与标题、颜色等导航栏状态一致,按路由路径缓存,同一路由的后续页面实例也会保持隐藏 this.setCacheValue() this.cache[this.pageContext.originPathname].homeButtonHidden = true this.setFnBtnState() From 315e90b71bd4e639a4b5e187edb1af050668c8c6 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Mon, 23 Nov 2026 14:00:01 +0530 Subject: [PATCH 3/7] fix(router): scope hideHomeButton to the page instance on H5 --- .../__tests__/navigation-bar-test.ts | 108 ++++++++++++++++-- .../taro-router/src/router/navigation-bar.ts | 19 ++- .../taro/types/api/ui/navigation-bar.d.ts | 2 +- 3 files changed, 114 insertions(+), 15 deletions(-) diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 702769c0bcb7..5af884bc1548 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -1,9 +1,12 @@ +import { createBrowserHistory } from 'history' + import NavigationBarHandler from '../src/router/navigation-bar' +import PageHandler from '../src/router/page' import stacks from '../src/router/stack' import { hideNavigationBarHomeButton } from '../src/utils/navigate' import type { PageInstance } from '@tarojs/runtime' -import type PageHandler from '../src/router/page' +import type { SpaRouterConfig } from '../types/router' const HOME_PAGE = '/pages/index/index' const OTHER_PAGE = '/pages/detail/index' @@ -111,7 +114,7 @@ describe('NavigationBarHandler', () => { expect(getFnBtn()).toBe('back') }) - it('only applies to the page that hid it', () => { + it('only applies to the page instance that hid it', () => { setStackSize(1) const handler = createHandler(OTHER_PAGE) handler.load() @@ -119,13 +122,10 @@ describe('NavigationBarHandler', () => { expect(getFnBtn()).toBe('none') const anotherPage = '/pages/another/index' + setStackSize(1) Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) handler.load() expect(getFnBtn()).toBe('home') - - Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE }) - handler.load() - expect(getFnBtn()).toBe('none') }) it('stays hidden after navigating to another page and back', () => { @@ -135,16 +135,108 @@ describe('NavigationBarHandler', () => { hideNavigationBarHomeButton() const anotherPage = '/pages/another/index' - setStackSize(2) + const original = stacks.last + stacks.push({} as PageInstance) Object.assign(handler.pageContext, { currentPage: anotherPage, originPathname: anotherPage }) handler.load() expect(getFnBtn()).toBe('back') - setStackSize(1) + stacks.pop() + expect(stacks.last).toBe(original) Object.assign(handler.pageContext, { currentPage: OTHER_PAGE, originPathname: OTHER_PAGE }) handler.load() expect(getFnBtn()).toBe('none') }) + + it('does not carry over to a new instance of the same route', () => { + setStackSize(1) + const handler = createHandler(OTHER_PAGE) + handler.load() + hideNavigationBarHomeButton() + expect(getFnBtn()).toBe('none') + + // 例如 reLaunch 到同一路由:旧实例出栈,新实例入栈且没有调用该接口 + setStackSize(1) + handler.load() + + expect(getFnBtn()).toBe('home') + }) + }) + + describe('hideHomeButton with the page handler', () => { + function createPage (path: string) { + return { + path, + options: {}, + $taroParams: { stamp: 'navigation-bar-test' }, + onShow: jest.fn(), + onHide: jest.fn(), + onUnload: jest.fn() + } as unknown as PageInstance + } + + function createContainer (page: PageInstance) { + const el = document.createElement('div') + el.id = page.path! + el.className = 'taro_page' + document.body.appendChild(el) + return el + } + + function createPageHandler (pathname: string) { + const config: SpaRouterConfig = { + pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], + routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], + router: { mode: 'browser', basename: '', pathname }, + window: { navigationStyle: 'default' } + } + return new PageHandler(config, createBrowserHistory()) + } + + // PageHandler 通过运行时的 location 获取当前路由,这里直接模拟路由切换 + let route = OTHER_PAGE + const setRoute = (pathname: string) => { + route = pathname + } + + afterEach(() => { + route = OTHER_PAGE + document.body.innerHTML = '' + }) + + it('stays hidden after navigateTo and navigateBack, and resets on a relaunched instance', () => { + const handler = createPageHandler(OTHER_PAGE) + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + const page = createPage(OTHER_PAGE) + createContainer(page) + // 页面在 onShow 中调用,此时路由还未刷新导航栏 + ;(page.onShow as jest.Mock).mockImplementation(() => hideNavigationBarHomeButton()) + + handler.load(page, {}, 'navigation-bar-test') + expect(getFnBtn()).toBe('none') + + // navigateTo 另一个页面 + const nextPage = createPage('/pages/another/index') + createContainer(nextPage) + handler.hide(page) + setRoute('/pages/another/index') + handler.load(nextPage, {}, 'navigation-bar-test') + expect(getFnBtn()).toBe('back') + + // navigateBack 回到原页面 + handler.unload(nextPage) + setRoute(OTHER_PAGE) + handler.show(page) + expect(getFnBtn()).toBe('none') + + // reLaunch 到同一路由的新实例,且没有调用该接口 + handler.unload(page) + setRoute(OTHER_PAGE) + const relaunched = createPage(OTHER_PAGE) + createContainer(relaunched) + handler.load(relaunched, {}, 'navigation-bar-test') + expect(getFnBtn()).toBe('home') + }) }) describe('setNavigationBarVisible', () => { diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index a9ef539ccefd..31ee62fe8f97 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -4,6 +4,7 @@ import { navigateBack, reLaunch } from '../api' import { isDingTalk } from '../utils' import stacks from './stack' +import type { PageInstance } from '@tarojs/runtime' import type PageHandler from './page' interface NavigationBarCache { @@ -12,7 +13,6 @@ interface NavigationBarCache { title?: string show?: boolean loading?: boolean - homeButtonHidden?: boolean } export default class NavigationBarHandler { @@ -20,6 +20,8 @@ export default class NavigationBarHandler { navigationBarElement: HTMLElement cache: Record isLoadDdEntry = false + // 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效 + homeButtonHiddenPages = new WeakSet() constructor (pageContext: PageHandler) { this.cache = {} @@ -107,18 +109,23 @@ export default class NavigationBarHandler { this.fnBtnToggleToNone() } else if (stacks.length > 1) { this.fnBtnToggleToBack() - } else if (this.pageContext.homePage === currentRouter || this.cache[this.pageContext.originPathname]?.homeButtonHidden) { + } else if (this.pageContext.homePage === currentRouter || this.isHomeButtonHidden()) { this.fnBtnToggleToNone() } else { this.fnBtnToggleToHome() } } + private isHomeButtonHidden () { + const page = stacks.last + return !!page && this.homeButtonHiddenPages.has(page) + } + hideHomeButton () { - // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,需要先初始化缓存,确保 load 时不会重新展示首页按钮 - // 与标题、颜色等导航栏状态一致,按路由路径缓存,同一路由的后续页面实例也会保持隐藏 - this.setCacheValue() - this.cache[this.pageContext.originPathname].homeButtonHidden = true + // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,但页面已入栈,直接记录在页面实例上,确保 load 时不会重新展示首页按钮 + const page = stacks.last + if (!page) return + this.homeButtonHiddenPages.add(page) this.setFnBtnState() } diff --git a/packages/taro/types/api/ui/navigation-bar.d.ts b/packages/taro/types/api/ui/navigation-bar.d.ts index b9a0658e7c87..b04cc5fb21dc 100644 --- a/packages/taro/types/api/ui/navigation-bar.d.ts +++ b/packages/taro/types/api/ui/navigation-bar.d.ts @@ -123,7 +123,7 @@ declare module '../../index' { /** 隐藏返回首页按钮。微信7.0.7版本起,当用户打开的小程序最底层页面是非首页时,默认展示“返回首页”按钮,开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏。 * @supported weapp, tt, h5, harmony - * @h5 隐藏当前页面 H5 导航栏中的返回首页按钮,不影响返回按钮 + * @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响 * @see https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.hideHomeButton.html */ hideHomeButton(option?: hideHomeButton.Option): Promise From e835be4df4578f3203f5144a8c298281c38fb390 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Mon, 23 Nov 2026 21:31:43 +0530 Subject: [PATCH 4/7] fix(router): ignore hideHomeButton calls made while a page is unloading A page is popped from the stack before its onUnload runs, so a hideHomeButton call from onUnload landed on the destination page. Skip the call while unloading, and make the navigate-back test only hide the button on the first onShow. --- .../__tests__/navigation-bar-test.ts | 47 ++++++++++++++++++- .../taro-router/src/router/navigation-bar.ts | 3 ++ packages/taro-router/src/router/page.ts | 16 +++++-- 3 files changed, 62 insertions(+), 4 deletions(-) diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 5af884bc1548..d1f466dca0a3 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -210,7 +210,7 @@ describe('NavigationBarHandler', () => { const page = createPage(OTHER_PAGE) createContainer(page) // 页面在 onShow 中调用,此时路由还未刷新导航栏 - ;(page.onShow as jest.Mock).mockImplementation(() => hideNavigationBarHomeButton()) + ;(page.onShow as jest.Mock).mockImplementationOnce(() => hideNavigationBarHomeButton()) handler.load(page, {}, 'navigation-bar-test') expect(getFnBtn()).toBe('none') @@ -239,6 +239,51 @@ describe('NavigationBarHandler', () => { }) }) + describe('hideHomeButton called while a page is unloading', () => { + it('does not hide the home button of the page navigated back to', () => { + const config: SpaRouterConfig = { + pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], + routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], + router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, + window: { navigationStyle: 'default' } + } + const handler = new PageHandler(config, createBrowserHistory()) + let route = OTHER_PAGE + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + const create = (path: string, onUnload?: () => void) => { + const el = document.createElement('div') + el.id = path + el.className = 'taro_page' + document.body.appendChild(el) + return { + path, + options: {}, + $taroParams: { stamp: 'navigation-bar-test' }, + onShow: jest.fn(), + onHide: jest.fn(), + onUnload: jest.fn(onUnload) + } as unknown as PageInstance + } + + const pageA = create(OTHER_PAGE) + handler.load(pageA, {}, 'navigation-bar-test') + expect(getFnBtn()).toBe('home') + + // B 在 onUnload 中调用该接口,此时 B 已出栈,栈顶是 A + const pageB = create('/pages/another/index', () => hideNavigationBarHomeButton()) + handler.hide(pageA) + route = '/pages/another/index' + handler.load(pageB, {}, 'navigation-bar-test') + handler.unload(pageB) + route = OTHER_PAGE + handler.show(pageA) + + expect(pageB.onUnload).toHaveBeenCalledTimes(1) + expect(getFnBtn()).toBe('home') + document.body.innerHTML = '' + }) + }) + describe('setNavigationBarVisible', () => { const isVisible = () => { const show = navigationBar.classList.contains('taro-navigation-bar-show') diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index 31ee62fe8f97..65370a169136 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -20,6 +20,8 @@ export default class NavigationBarHandler { navigationBarElement: HTMLElement cache: Record isLoadDdEntry = false + // 页面卸载中(已出栈)时,忽略对栈顶页面的首页按钮设置 + isPageUnloading = false // 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效 homeButtonHiddenPages = new WeakSet() @@ -123,6 +125,7 @@ export default class NavigationBarHandler { hideHomeButton () { // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,但页面已入栈,直接记录在页面实例上,确保 load 时不会重新展示首页按钮 + if (this.isPageUnloading) return const page = stacks.last if (!page) return this.homeButtonHiddenPages.add(page) diff --git a/packages/taro-router/src/router/page.ts b/packages/taro-router/src/router/page.ts index b8c326a46720..7b893740b3d9 100644 --- a/packages/taro-router/src/router/page.ts +++ b/packages/taro-router/src/router/page.ts @@ -202,6 +202,16 @@ export default class PageHandler { } } + // Note: 页面出栈后才会执行 onUnload,此时栈顶已是目标页面,需要避免已出栈页面的导航栏调用作用到目标页面 + protected triggerUnload (page?: PageInstance | null) { + this.navigationBarHandler.isPageUnloading = true + try { + page?.onUnload?.() + } finally { + this.navigationBarHandler.isPageUnloading = false + } + } + unload (page?: PageInstance | null, delta = 1, top = false) { if (!page) return @@ -210,7 +220,7 @@ export default class PageHandler { if (this.animation && top) { if (this.unloadTimer) { clearTimeout(this.unloadTimer) - this.lastUnloadPage?.onUnload?.() + this.triggerUnload(this.lastUnloadPage) this.unloadTimer = null } this.lastUnloadPage = page @@ -223,14 +233,14 @@ export default class PageHandler { this.unloadTimer = setTimeout(() => { this.unloadTimer = null - this.lastUnloadPage?.onUnload?.() + this.triggerUnload(this.lastUnloadPage) eventCenter.trigger('__taroPageOnShowAfterDestroyed') }, this.animationDuration) } else { const pageEl = this.getPageContainer(page) pageEl?.classList.remove('taro_page_stationed') pageEl?.classList.remove('taro_page_show') - page?.onUnload?.() + this.triggerUnload(page) setTimeout(() => { eventCenter.trigger('__taroPageOnShowAfterDestroyed') }, 0) From 9832376ec3bec0d0f1c37e097ad18349118af068 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Tue, 24 Nov 2026 10:16:27 +0530 Subject: [PATCH 5/7] fix(router): ignore deferred hideHomeButton calls from a popped page Keep ignoring hideHomeButton until the macrotask after onUnload, so calls deferred through a microtask can no longer hide the destination page's home button. onShow of the page shown right after an unload is exempt. Co-authored-by: dhananjay6561 <133662894+dhananjay6561@users.noreply.github.com> Signed-off-by: Asish Kumar --- .../__tests__/navigation-bar-test.ts | 90 +++++++++++++++++++ .../taro-router/src/router/navigation-bar.ts | 1 + packages/taro-router/src/router/page.ts | 30 +++++-- 3 files changed, 115 insertions(+), 6 deletions(-) diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index d1f466dca0a3..0588cbd0672f 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -282,6 +282,96 @@ describe('NavigationBarHandler', () => { expect(getFnBtn()).toBe('home') document.body.innerHTML = '' }) + + it('ignores a call deferred by a microtask from the popped page', async () => { + const config: SpaRouterConfig = { + pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], + routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], + router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, + window: { navigationStyle: 'default' } + } + const handler = new PageHandler(config, createBrowserHistory()) + let route = OTHER_PAGE + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + const create = (path: string, onUnload?: () => void) => { + const el = document.createElement('div') + el.id = path + el.className = 'taro_page' + document.body.appendChild(el) + return { + path, + options: {}, + $taroParams: { stamp: 'navigation-bar-test' }, + onShow: jest.fn(), + onHide: jest.fn(), + onUnload: jest.fn(onUnload) + } as unknown as PageInstance + } + + const pageA = create(OTHER_PAGE) + handler.load(pageA, {}, 'navigation-bar-test') + expect(getFnBtn()).toBe('home') + + // B 在 onUnload 中通过微任务延后调用该接口 + let deferred: Promise = Promise.resolve() + const pageB = create('/pages/another/index', () => { + deferred = Promise.resolve().then(() => hideNavigationBarHomeButton()) + }) + handler.hide(pageA) + route = '/pages/another/index' + handler.load(pageB, {}, 'navigation-bar-test') + handler.unload(pageB) + route = OTHER_PAGE + handler.show(pageA) + await deferred + await new Promise(resolve => setTimeout(resolve, 0)) + + expect(getFnBtn()).toBe('home') + + // 卸载结束后,A 自己调用仍然生效 + hideNavigationBarHomeButton() + expect(getFnBtn()).toBe('none') + document.body.innerHTML = '' + }) + + it('still applies a call made in onShow of the page shown right after the unload', () => { + const config: SpaRouterConfig = { + pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], + routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], + router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, + window: { navigationStyle: 'default' } + } + const handler = new PageHandler(config, createBrowserHistory()) + let route = OTHER_PAGE + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + const create = (path: string) => { + const el = document.createElement('div') + el.id = path + el.className = 'taro_page' + document.body.appendChild(el) + return { + path, + options: {}, + $taroParams: { stamp: 'navigation-bar-test' }, + onShow: jest.fn(), + onHide: jest.fn(), + onUnload: jest.fn() + } as unknown as PageInstance + } + + const pageA = create(OTHER_PAGE) + handler.load(pageA, {}, 'navigation-bar-test') + + // reLaunch:旧页面卸载后立即加载新页面,新页面在 onShow 中隐藏首页按钮 + const pageB = create('/pages/another/index') + ;(pageB.onShow as jest.Mock).mockImplementationOnce(() => hideNavigationBarHomeButton()) + handler.unload(pageA) + route = '/pages/another/index' + handler.load(pageB, {}, 'navigation-bar-test') + + expect(getFnBtn()).toBe('none') + document.body.innerHTML = '' + }) }) describe('setNavigationBarVisible', () => { diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index 65370a169136..703082d20b30 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -22,6 +22,7 @@ export default class NavigationBarHandler { isLoadDdEntry = false // 页面卸载中(已出栈)时,忽略对栈顶页面的首页按钮设置 isPageUnloading = false + unloadingCount = 0 // 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效 homeButtonHiddenPages = new WeakSet() diff --git a/packages/taro-router/src/router/page.ts b/packages/taro-router/src/router/page.ts index 7b893740b3d9..6896120860d3 100644 --- a/packages/taro-router/src/router/page.ts +++ b/packages/taro-router/src/router/page.ts @@ -182,7 +182,7 @@ export default class PageHandler { this.isTabBar(this.pathname) && pageEl.classList.add('taro_tabbar_page') this.isDefaultNavigationStyle() && pageEl.classList.add('taro_navigation_page') this.addAnimation(pageEl, pageNo === 0) - page.onShow?.() + this.triggerShow(page) this.navigationBarHandler.load() this.bindPageEvents(page, pageConfig) this.triggerRouterChange() @@ -193,7 +193,7 @@ export default class PageHandler { this.isTabBar(this.pathname) && pageEl?.classList.add('taro_tabbar_page') this.isDefaultNavigationStyle() && pageEl?.classList.add('taro_navigation_page') this.addAnimation(pageEl, pageNo === 0) - page.onShow?.() + this.triggerShow(page) this.navigationBarHandler.load() this.onReady(page, true) this.bindPageEvents(page, pageConfig) @@ -203,12 +203,30 @@ export default class PageHandler { } // Note: 页面出栈后才会执行 onUnload,此时栈顶已是目标页面,需要避免已出栈页面的导航栏调用作用到目标页面 + // 忽略范围包含 onUnload 中通过 Promise 等微任务延后的调用,因此在宏任务中才恢复 protected triggerUnload (page?: PageInstance | null) { - this.navigationBarHandler.isPageUnloading = true + const handler = this.navigationBarHandler + handler.isPageUnloading = true + handler.unloadingCount++ try { page?.onUnload?.() } finally { - this.navigationBarHandler.isPageUnloading = false + setTimeout(() => { + handler.unloadingCount = Math.max(handler.unloadingCount - 1, 0) + if (handler.unloadingCount === 0) handler.isPageUnloading = false + }, 0) + } + } + + // Note: 页面 onShow 中的调用属于新展示的页面,不应被卸载窗口忽略 + protected triggerShow (page: PageInstance) { + const handler = this.navigationBarHandler + const isPageUnloading = handler.isPageUnloading + handler.isPageUnloading = false + try { + page.onShow?.() + } finally { + handler.isPageUnloading = isPageUnloading } } @@ -261,7 +279,7 @@ export default class PageHandler { } pageEl.classList.remove('taro_page_shade') this.addAnimation(pageEl, pageNo === 0) - page.onShow?.() + this.triggerShow(page) this.navigationBarHandler.load() this.bindPageEvents(page, pageConfig) this.triggerRouterChange() @@ -269,7 +287,7 @@ export default class PageHandler { page.onLoad?.(param, () => { pageEl = this.getPageContainer(page) this.addAnimation(pageEl, pageNo === 0) - page.onShow?.() + this.triggerShow(page) this.navigationBarHandler.load() this.onReady(page, false) this.bindPageEvents(page, pageConfig) From 27bb7ca0123008c4030d4cd5b78e2071d808857d Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Tue, 24 Nov 2026 15:53:31 +0530 Subject: [PATCH 6/7] fix(router): attribute hideHomeButton calls to the page that made them Compare Current.page with the stack top instead of ignoring every call for a macrotask after onUnload. A popped page's call deferred by a microtask now runs while Current.page still points at it, and the shown page's own onShow call is no longer rejected. Tests use the real createPageConfig, with and without animation. --- .../__tests__/navigation-bar-test.ts | 328 ++++++++---------- .../taro-router/src/router/navigation-bar.ts | 8 +- packages/taro-router/src/router/page.ts | 29 +- 3 files changed, 164 insertions(+), 201 deletions(-) diff --git a/packages/taro-router/__tests__/navigation-bar-test.ts b/packages/taro-router/__tests__/navigation-bar-test.ts index 0588cbd0672f..0862c9174406 100644 --- a/packages/taro-router/__tests__/navigation-bar-test.ts +++ b/packages/taro-router/__tests__/navigation-bar-test.ts @@ -1,3 +1,4 @@ +import { Current, createPageConfig, document as taroDocument, injectPageInstance } from '@tarojs/runtime' import { createBrowserHistory } from 'history' import NavigationBarHandler from '../src/router/navigation-bar' @@ -27,6 +28,12 @@ function createHandler (currentPage: string, options: { } as unknown as PageHandler) } +// 页面的生命周期执行时,Current.page 指向该页面 +function hideAsCurrentPage () { + Current.page = stacks.last as any + hideNavigationBarHomeButton() +} + function setStackSize (size: number) { while (stacks.length > 0) stacks.pop() for (let i = 0; i < size; i++) stacks.push({} as PageInstance) @@ -88,7 +95,7 @@ describe('NavigationBarHandler', () => { handler.load() expect(getFnBtn()).toBe('home') - hideNavigationBarHomeButton() + hideAsCurrentPage() expect(getFnBtn()).toBe('none') }) @@ -98,7 +105,7 @@ describe('NavigationBarHandler', () => { const handler = createHandler(OTHER_PAGE) // 页面在 onShow 中调用时,导航栏还未根据当前页面刷新 - hideNavigationBarHomeButton() + hideAsCurrentPage() handler.load() expect(getFnBtn()).toBe('none') @@ -109,7 +116,7 @@ describe('NavigationBarHandler', () => { const handler = createHandler(OTHER_PAGE) handler.load() - hideNavigationBarHomeButton() + hideAsCurrentPage() expect(getFnBtn()).toBe('back') }) @@ -118,7 +125,7 @@ describe('NavigationBarHandler', () => { setStackSize(1) const handler = createHandler(OTHER_PAGE) handler.load() - hideNavigationBarHomeButton() + hideAsCurrentPage() expect(getFnBtn()).toBe('none') const anotherPage = '/pages/another/index' @@ -132,7 +139,7 @@ describe('NavigationBarHandler', () => { setStackSize(1) const handler = createHandler(OTHER_PAGE) handler.load() - hideNavigationBarHomeButton() + hideAsCurrentPage() const anotherPage = '/pages/another/index' const original = stacks.last @@ -152,7 +159,7 @@ describe('NavigationBarHandler', () => { setStackSize(1) const handler = createHandler(OTHER_PAGE) handler.load() - hideNavigationBarHomeButton() + hideAsCurrentPage() expect(getFnBtn()).toBe('none') // 例如 reLaunch 到同一路由:旧实例出栈,新实例入栈且没有调用该接口 @@ -163,214 +170,187 @@ describe('NavigationBarHandler', () => { }) }) - describe('hideHomeButton with the page handler', () => { - function createPage (path: string) { - return { - path, - options: {}, - $taroParams: { stamp: 'navigation-bar-test' }, - onShow: jest.fn(), - onHide: jest.fn(), - onUnload: jest.fn() - } as unknown as PageInstance + describe('hideHomeButton with the real page config', () => { + const ANOTHER_PAGE = '/pages/another/index' + const STAMP = 'navigation-bar-test' + + type Lifecycles = Partial void>> + + let route = OTHER_PAGE + let handler: PageHandler + + // 与 connect 一致:挂载页面时创建页面容器并注册页面实例,用户生命周期通过 safeExecute 在 hasLoaded 之后执行 + function createPage (path: string, lifecycles: Lifecycles = {}) { + const component = { onShow: jest.fn(lifecycles.onShow), onUnload: jest.fn(lifecycles.onUnload) } + Current.app = { + mount: (_component, $taroPath, cb) => { + const el = document.createElement('div') + el.id = $taroPath + el.className = 'taro_page' + document.body.appendChild(el) + const root = taroDocument.createElement('root') + root.id = $taroPath + taroDocument.body.appendChild(root) + injectPageInstance(component as any, $taroPath) + cb() + }, + unmount: (_$taroPath, cb) => cb() + } as any + const page = createPageConfig(component, path, {}, {}) as unknown as PageInstance + page.options = { stamp: STAMP } + return { page, component } + } + + function load (page: PageInstance, path: string) { + route = path + handler.load(page, {}, STAMP) + } + + function back (from: PageInstance, to: PageInstance, path: string) { + handler.unload(from, 1) + route = path + handler.show(to) } - function createContainer (page: PageInstance) { - const el = document.createElement('div') - el.id = page.path! - el.className = 'taro_page' - document.body.appendChild(el) - return el + // 用户的 onShow 在 Promise 回调中执行,需要等待微任务 + const flush = async () => { + for (let i = 0; i < 5; i++) await Promise.resolve() } - function createPageHandler (pathname: string) { + // H5 端页面路径会写入页面配置,同时页面挂载后同步执行回调 + const platform = process.env.TARO_PLATFORM + beforeAll(() => { + process.env.TARO_PLATFORM = 'web' + }) + + afterAll(() => { + process.env.TARO_PLATFORM = platform + }) + + beforeEach(() => { + route = OTHER_PAGE const config: SpaRouterConfig = { pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], - routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], - router: { mode: 'browser', basename: '', pathname }, + routes: [{ path: HOME_PAGE }, { path: OTHER_PAGE }, { path: ANOTHER_PAGE }], + router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, window: { navigationStyle: 'default' } } - return new PageHandler(config, createBrowserHistory()) - } - - // PageHandler 通过运行时的 location 获取当前路由,这里直接模拟路由切换 - let route = OTHER_PAGE - const setRoute = (pathname: string) => { - route = pathname - } + handler = new PageHandler(config, createBrowserHistory()) + jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) + }) afterEach(() => { - route = OTHER_PAGE + jest.useRealTimers() + Current.page = null document.body.innerHTML = '' }) - it('stays hidden after navigateTo and navigateBack, and resets on a relaunched instance', () => { - const handler = createPageHandler(OTHER_PAGE) - jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) - const page = createPage(OTHER_PAGE) - createContainer(page) - // 页面在 onShow 中调用,此时路由还未刷新导航栏 - ;(page.onShow as jest.Mock).mockImplementationOnce(() => hideNavigationBarHomeButton()) - - handler.load(page, {}, 'navigation-bar-test') + it('stays hidden after navigateTo and navigateBack, and resets on a relaunched instance', async () => { + const { page: pageA, component: a } = createPage(OTHER_PAGE) + // 只在第一次 onShow 中调用 + a.onShow.mockImplementationOnce(() => hideNavigationBarHomeButton()) + load(pageA, OTHER_PAGE) + await flush() expect(getFnBtn()).toBe('none') - // navigateTo 另一个页面 - const nextPage = createPage('/pages/another/index') - createContainer(nextPage) - handler.hide(page) - setRoute('/pages/another/index') - handler.load(nextPage, {}, 'navigation-bar-test') + const { page: pageB } = createPage(ANOTHER_PAGE) + handler.hide(pageA) + load(pageB, ANOTHER_PAGE) + await flush() expect(getFnBtn()).toBe('back') - // navigateBack 回到原页面 - handler.unload(nextPage) - setRoute(OTHER_PAGE) - handler.show(page) + back(pageB, pageA, OTHER_PAGE) + await flush() + expect(a.onShow).toHaveBeenCalledTimes(2) expect(getFnBtn()).toBe('none') // reLaunch 到同一路由的新实例,且没有调用该接口 - handler.unload(page) - setRoute(OTHER_PAGE) - const relaunched = createPage(OTHER_PAGE) - createContainer(relaunched) - handler.load(relaunched, {}, 'navigation-bar-test') + handler.unload(pageA) + const { page: relaunched } = createPage(OTHER_PAGE) + load(relaunched, OTHER_PAGE) + await flush() expect(getFnBtn()).toBe('home') }) - }) - describe('hideHomeButton called while a page is unloading', () => { - it('does not hide the home button of the page navigated back to', () => { - const config: SpaRouterConfig = { - pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], - routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], - router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, - window: { navigationStyle: 'default' } + describe.each([ + ['without animation', false], + ['with animation', true] + ])('on the page navigated back to %s', (_name, animated) => { + async function openAThenB (lifecyclesB: Lifecycles = {}, lifecyclesA: Lifecycles = {}) { + const a = createPage(OTHER_PAGE, lifecyclesA) + load(a.page, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('home') + + const b = createPage(ANOTHER_PAGE, lifecyclesB) + handler.hide(a.page) + load(b.page, ANOTHER_PAGE) + await flush() + return { a, b } } - const handler = new PageHandler(config, createBrowserHistory()) - let route = OTHER_PAGE - jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) - const create = (path: string, onUnload?: () => void) => { - const el = document.createElement('div') - el.id = path - el.className = 'taro_page' - document.body.appendChild(el) - return { - path, - options: {}, - $taroParams: { stamp: 'navigation-bar-test' }, - onShow: jest.fn(), - onHide: jest.fn(), - onUnload: jest.fn(onUnload) - } as unknown as PageInstance + + // 带动画时页面在动画结束后才卸载,之后再展示目标页面 + async function goBack (from: PageInstance, to: PageInstance) { + if (animated) { + jest.useFakeTimers() + handler.unload(from, 1, true) + await jest.advanceTimersByTimeAsync(handler.animationDuration) + route = OTHER_PAGE + handler.show(to) + } else { + back(from, to, OTHER_PAGE) + } + await flush() } - const pageA = create(OTHER_PAGE) - handler.load(pageA, {}, 'navigation-bar-test') - expect(getFnBtn()).toBe('home') + it('does not hide the home button when the popped page calls it synchronously in onUnload', async () => { + const { a, b } = await openAThenB({ onUnload: () => hideNavigationBarHomeButton() }) - // B 在 onUnload 中调用该接口,此时 B 已出栈,栈顶是 A - const pageB = create('/pages/another/index', () => hideNavigationBarHomeButton()) - handler.hide(pageA) - route = '/pages/another/index' - handler.load(pageB, {}, 'navigation-bar-test') - handler.unload(pageB) - route = OTHER_PAGE - handler.show(pageA) + await goBack(b.page, a.page) - expect(pageB.onUnload).toHaveBeenCalledTimes(1) - expect(getFnBtn()).toBe('home') - document.body.innerHTML = '' - }) + expect(b.component.onUnload).toHaveBeenCalledTimes(1) + expect(getFnBtn()).toBe('home') + }) - it('ignores a call deferred by a microtask from the popped page', async () => { - const config: SpaRouterConfig = { - pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], - routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], - router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, - window: { navigationStyle: 'default' } - } - const handler = new PageHandler(config, createBrowserHistory()) - let route = OTHER_PAGE - jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) - const create = (path: string, onUnload?: () => void) => { - const el = document.createElement('div') - el.id = path - el.className = 'taro_page' - document.body.appendChild(el) - return { - path, - options: {}, - $taroParams: { stamp: 'navigation-bar-test' }, - onShow: jest.fn(), - onHide: jest.fn(), - onUnload: jest.fn(onUnload) - } as unknown as PageInstance - } + it('does not hide the home button when the popped page calls it from a microtask in onUnload', async () => { + let deferred: Promise = Promise.resolve() + const { a, b } = await openAThenB({ + onUnload: () => { + deferred = Promise.resolve().then(() => hideNavigationBarHomeButton()) + } + }) - const pageA = create(OTHER_PAGE) - handler.load(pageA, {}, 'navigation-bar-test') - expect(getFnBtn()).toBe('home') + await goBack(b.page, a.page) + await deferred - // B 在 onUnload 中通过微任务延后调用该接口 - let deferred: Promise = Promise.resolve() - const pageB = create('/pages/another/index', () => { - deferred = Promise.resolve().then(() => hideNavigationBarHomeButton()) + expect(b.component.onUnload).toHaveBeenCalledTimes(1) + expect(getFnBtn()).toBe('home') }) - handler.hide(pageA) - route = '/pages/another/index' - handler.load(pageB, {}, 'navigation-bar-test') - handler.unload(pageB) - route = OTHER_PAGE - handler.show(pageA) - await deferred - await new Promise(resolve => setTimeout(resolve, 0)) - expect(getFnBtn()).toBe('home') + it('applies a call made in onShow when the page is shown again', async () => { + const { a, b } = await openAThenB() + // 只在返回后的第二次 onShow 中调用 + a.component.onShow.mockImplementationOnce(() => hideNavigationBarHomeButton()) - // 卸载结束后,A 自己调用仍然生效 - hideNavigationBarHomeButton() - expect(getFnBtn()).toBe('none') - document.body.innerHTML = '' - }) + await goBack(b.page, a.page) - it('still applies a call made in onShow of the page shown right after the unload', () => { - const config: SpaRouterConfig = { - pages: ['pages/index/index', 'pages/detail/index', 'pages/another/index'], - routes: [{ path: '/pages/index/index' }, { path: OTHER_PAGE }, { path: '/pages/another/index' }], - router: { mode: 'browser', basename: '', pathname: OTHER_PAGE }, - window: { navigationStyle: 'default' } - } - const handler = new PageHandler(config, createBrowserHistory()) - let route = OTHER_PAGE - jest.spyOn(handler, 'currentPage', 'get').mockImplementation(() => route) - const create = (path: string) => { - const el = document.createElement('div') - el.id = path - el.className = 'taro_page' - document.body.appendChild(el) - return { - path, - options: {}, - $taroParams: { stamp: 'navigation-bar-test' }, - onShow: jest.fn(), - onHide: jest.fn(), - onUnload: jest.fn() - } as unknown as PageInstance - } + expect(a.component.onShow).toHaveBeenCalledTimes(2) + expect(getFnBtn()).toBe('none') + }) + }) - const pageA = create(OTHER_PAGE) - handler.load(pageA, {}, 'navigation-bar-test') + it('applies a call made in onShow of a page opened by reLaunch', async () => { + const { page: pageA } = createPage(OTHER_PAGE) + load(pageA, OTHER_PAGE) + await flush() + expect(getFnBtn()).toBe('home') - // reLaunch:旧页面卸载后立即加载新页面,新页面在 onShow 中隐藏首页按钮 - const pageB = create('/pages/another/index') - ;(pageB.onShow as jest.Mock).mockImplementationOnce(() => hideNavigationBarHomeButton()) handler.unload(pageA) - route = '/pages/another/index' - handler.load(pageB, {}, 'navigation-bar-test') + const { page: relaunched } = createPage(ANOTHER_PAGE, { onShow: () => hideNavigationBarHomeButton() }) + load(relaunched, ANOTHER_PAGE) + await flush() expect(getFnBtn()).toBe('none') - document.body.innerHTML = '' }) }) diff --git a/packages/taro-router/src/router/navigation-bar.ts b/packages/taro-router/src/router/navigation-bar.ts index 703082d20b30..cdf9cde46de4 100644 --- a/packages/taro-router/src/router/navigation-bar.ts +++ b/packages/taro-router/src/router/navigation-bar.ts @@ -1,4 +1,4 @@ -import { eventCenter } from '@tarojs/runtime' +import { Current, eventCenter } from '@tarojs/runtime' import { navigateBack, reLaunch } from '../api' import { isDingTalk } from '../utils' @@ -20,9 +20,8 @@ export default class NavigationBarHandler { navigationBarElement: HTMLElement cache: Record isLoadDdEntry = false - // 页面卸载中(已出栈)时,忽略对栈顶页面的首页按钮设置 + // 页面在 onUnload 中(已出栈)时,忽略对栈顶页面的首页按钮设置 isPageUnloading = false - unloadingCount = 0 // 按页面实例记录已隐藏首页按钮的页面,页面实例销毁后状态随之失效 homeButtonHiddenPages = new WeakSet() @@ -128,7 +127,8 @@ export default class NavigationBarHandler { // Note: 页面通常在 onShow 中调用,此时 load 尚未执行,但页面已入栈,直接记录在页面实例上,确保 load 时不会重新展示首页按钮 if (this.isPageUnloading) return const page = stacks.last - if (!page) return + // Note: Current.page 是最近一次执行生命周期的页面。已出栈页面在 onUnload 中通过微任务延后的调用,会早于目标页面的 onShow,此时它不是栈顶页面 + if (!page || Current.page !== page) return this.homeButtonHiddenPages.add(page) this.setFnBtnState() } diff --git a/packages/taro-router/src/router/page.ts b/packages/taro-router/src/router/page.ts index 6896120860d3..e6ce3eadd89c 100644 --- a/packages/taro-router/src/router/page.ts +++ b/packages/taro-router/src/router/page.ts @@ -182,7 +182,7 @@ export default class PageHandler { this.isTabBar(this.pathname) && pageEl.classList.add('taro_tabbar_page') this.isDefaultNavigationStyle() && pageEl.classList.add('taro_navigation_page') this.addAnimation(pageEl, pageNo === 0) - this.triggerShow(page) + page.onShow?.() this.navigationBarHandler.load() this.bindPageEvents(page, pageConfig) this.triggerRouterChange() @@ -193,7 +193,7 @@ export default class PageHandler { this.isTabBar(this.pathname) && pageEl?.classList.add('taro_tabbar_page') this.isDefaultNavigationStyle() && pageEl?.classList.add('taro_navigation_page') this.addAnimation(pageEl, pageNo === 0) - this.triggerShow(page) + page.onShow?.() this.navigationBarHandler.load() this.onReady(page, true) this.bindPageEvents(page, pageConfig) @@ -202,31 +202,14 @@ export default class PageHandler { } } - // Note: 页面出栈后才会执行 onUnload,此时栈顶已是目标页面,需要避免已出栈页面的导航栏调用作用到目标页面 - // 忽略范围包含 onUnload 中通过 Promise 等微任务延后的调用,因此在宏任务中才恢复 + // Note: 页面出栈后才会执行 onUnload,此时栈顶已是目标页面,需要避免已出栈页面在 onUnload 中同步调用的导航栏方法作用到目标页面 protected triggerUnload (page?: PageInstance | null) { const handler = this.navigationBarHandler handler.isPageUnloading = true - handler.unloadingCount++ try { page?.onUnload?.() } finally { - setTimeout(() => { - handler.unloadingCount = Math.max(handler.unloadingCount - 1, 0) - if (handler.unloadingCount === 0) handler.isPageUnloading = false - }, 0) - } - } - - // Note: 页面 onShow 中的调用属于新展示的页面,不应被卸载窗口忽略 - protected triggerShow (page: PageInstance) { - const handler = this.navigationBarHandler - const isPageUnloading = handler.isPageUnloading - handler.isPageUnloading = false - try { - page.onShow?.() - } finally { - handler.isPageUnloading = isPageUnloading + handler.isPageUnloading = false } } @@ -279,7 +262,7 @@ export default class PageHandler { } pageEl.classList.remove('taro_page_shade') this.addAnimation(pageEl, pageNo === 0) - this.triggerShow(page) + page.onShow?.() this.navigationBarHandler.load() this.bindPageEvents(page, pageConfig) this.triggerRouterChange() @@ -287,7 +270,7 @@ export default class PageHandler { page.onLoad?.(param, () => { pageEl = this.getPageContainer(page) this.addAnimation(pageEl, pageNo === 0) - this.triggerShow(page) + page.onShow?.() this.navigationBarHandler.load() this.onReady(page, false) this.bindPageEvents(page, pageConfig) From 11b4d97b5d741bcde8870b32add1d769adca115b Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Thu, 26 Nov 2026 11:25:15 +0530 Subject: [PATCH 7/7] docs(types): note onShow usage and delayed-call scope for H5 hideHomeButton --- packages/taro/types/api/ui/navigation-bar.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/taro/types/api/ui/navigation-bar.d.ts b/packages/taro/types/api/ui/navigation-bar.d.ts index b04cc5fb21dc..2e887684926d 100644 --- a/packages/taro/types/api/ui/navigation-bar.d.ts +++ b/packages/taro/types/api/ui/navigation-bar.d.ts @@ -123,7 +123,7 @@ declare module '../../index' { /** 隐藏返回首页按钮。微信7.0.7版本起,当用户打开的小程序最底层页面是非首页时,默认展示“返回首页”按钮,开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏。 * @supported weapp, tt, h5, harmony - * @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响 + * @h5 隐藏当前页面实例 H5 导航栏中的返回首页按钮,不影响返回按钮;通过 reLaunch 等方式重新打开的页面不受影响。建议在需要隐藏按钮的页面的 onShow 中调用;延迟执行的调用(例如在 onUnload 中设置的定时器)会作用于执行时的当前页面,可能会隐藏用户返回后所在页面的按钮 * @see https://developers.weixin.qq.com/miniprogram/dev/api/ui/navigation-bar/wx.hideHomeButton.html */ hideHomeButton(option?: hideHomeButton.Option): Promise