When clicking <a> tag with no href, don't attempt navigation to "null". Fixes #943

This commit is contained in:
Steve Sanderson 2018-06-07 13:12:36 +01:00
parent 0fb47684c8
commit a1e613b717
3 changed files with 22 additions and 3 deletions

View File

@ -19,9 +19,11 @@ registerFunction(`${registeredFunctionPrefix}.enableNavigationInterception`, ()
document.addEventListener('click', event => {
// Intercept clicks on all <a> elements where the href is within the <base href> 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

View File

@ -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<TestRouter>();
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

View File

@ -16,3 +16,7 @@
<button onclick=@(x => uriHelper.NavigateTo("Other"))>
Programmatic navigation
</button>
<a id="anchor-with-no-href">
Anchor tag with no href attribute
</a>