diff --git a/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts b/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts index 4200864dab..734fe80a24 100644 --- a/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts +++ b/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts @@ -19,9 +19,11 @@ registerFunction(`${registeredFunctionPrefix}.enableNavigationInterception`, () document.addEventListener('click', event => { // Intercept clicks on all elements where the href is within the URI space - const anchorTarget = findClosestAncestor(event.target as Element | null, 'A'); - if (anchorTarget) { - const href = anchorTarget.getAttribute('href'); + // We must explicitly check if it has an 'href' attribute, because if it doesn't, the result might be null or an empty string depending on the browser + const anchorTarget = findClosestAncestor(event.target as Element | null, 'A') as HTMLAnchorElement; + const hrefAttributeName = 'href'; + if (anchorTarget && anchorTarget.hasAttribute(hrefAttributeName)) { + const href = anchorTarget.getAttribute(hrefAttributeName)!; const absoluteHref = toAbsoluteUri(href); // Don't stop ctrl/meta-click (etc) from opening links in new tabs/windows diff --git a/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs b/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs index ebe8b0fac8..759722e8c0 100644 --- a/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs +++ b/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs @@ -231,6 +231,19 @@ namespace Microsoft.AspNetCore.Blazor.E2ETest.Tests AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)"); } + [Fact] + public void ClickingAnchorWithNoHrefShouldNotNavigate() + { + SetUrlViaPushState($"{ServerPathBase}/"); + var initialUrl = Browser.Url; + + var app = MountTestComponent(); + app.FindElement(By.Id("anchor-with-no-href")).Click(); + + Assert.Equal(initialUrl, Browser.Url); + AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)"); + } + public void Dispose() { // Clear any existing state diff --git a/test/testapps/BasicTestApp/RouterTest/Links.cshtml b/test/testapps/BasicTestApp/RouterTest/Links.cshtml index a57098f9c7..208f9d81cc 100644 --- a/test/testapps/BasicTestApp/RouterTest/Links.cshtml +++ b/test/testapps/BasicTestApp/RouterTest/Links.cshtml @@ -16,3 +16,7 @@ + + + Anchor tag with no href attribute +