Skip to content

Commit

Permalink
[web] Remove /#/ from home page URL (#42598)
Browse files Browse the repository at this point in the history
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 flutter/flutter#127608
  • Loading branch information
mdebbar committed Jun 6, 2023
1 parent ca49946 commit 6f9df0f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/web_ui/lib/ui_web/src/ui_web/navigation/url_strategy.dart
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,17 @@ class HashUrlStrategy implements UrlStrategy {
// 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
Expand Down
17 changes: 17 additions & 0 deletions lib/web_ui/test/engine/history_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,23 @@ void testMain() {
);
});

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';
Expand Down

0 comments on commit 6f9df0f

Please sign in to comment.