[web] Remove /#/ from home page URL (#42598)
To make the `HashUrlStrategy` a bit cleaner (at least for the home page), let's get rid of the notorious `/#/` when the app is in the home page.
Non-home pages continue to have a hash in them. After this PR, here are some example URL changes:
- `http://domain.com/#/` => `http://domain.com/`
- `http://domain.com/#/page1` => (remains the same)
This change is backwards compatible, i.e. if you write `http://domain.com/#/` in the address bar, the app will load and open the home page correctly; and flutter will automatically change the URL to `http://domain.com/`.
Fixes https://github.com/flutter/flutter/issues/127608
diff --git a/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart b/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart
index 4d9e383..7932221 100644
--- a/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart
+++ b/lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart
@@ -179,8 +179,17 @@
// if the empty URL is pushed it won't replace any existing fragment. So
// when the hash path is empty, we still return the location's path and
// query.
- return '${_platformLocation.pathname}${_platformLocation.search}'
- '${internalUrl.isEmpty ? '' : '#$internalUrl'}';
+ final String hash;
+ if (internalUrl.isEmpty || internalUrl == '/') {
+ // Let's not add the hash at all when the app is in the home page. That
+ // way, the URL of the home page is cleaner.
+ //
+ // See: https://github.com/flutter/flutter/issues/127608
+ hash = '';
+ } else {
+ hash = '#$internalUrl';
+ }
+ return '${_platformLocation.pathname}${_platformLocation.search}$hash';
}
@override
diff --git a/lib/web_ui/test/engine/history_test.dart b/lib/web_ui/test/engine/history_test.dart
index b661385..e34c452 100644
--- a/lib/web_ui/test/engine/history_test.dart
+++ b/lib/web_ui/test/engine/history_test.dart
@@ -663,6 +663,23 @@
);
});
+ test('removes /#/ from the home page', () {
+ const String internalUrl = '/';
+ final HashUrlStrategy strategy = HashUrlStrategy(location);
+
+ location.pathname = '/';
+ expect(strategy.prepareExternalUrl(internalUrl), '/');
+
+ location.pathname = '/main';
+ expect(strategy.prepareExternalUrl(internalUrl), '/main');
+
+ location.search = '?foo=bar';
+ expect(
+ strategy.prepareExternalUrl(internalUrl),
+ '/main?foo=bar',
+ );
+ });
+
test('addPopStateListener fn unwraps DomPopStateEvent state', () {
final HashUrlStrategy strategy = HashUrlStrategy(location);
const String expected = 'expected value';