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 6085acd76fd1560d52ff71c71949bee0207243fe..169916d8adc16be55075fa65601239c88b69b6c1 100644 --- a/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts +++ b/src/Microsoft.AspNetCore.Blazor.Browser.JS/src/Services/UriHelper.ts @@ -27,9 +27,11 @@ function enableNavigationInterception(assemblyName: string, functionName: string if (anchorTarget && anchorTarget.hasAttribute(hrefAttributeName) && event.button === 0) { const href = anchorTarget.getAttribute(hrefAttributeName)!; const absoluteHref = toAbsoluteUri(href); + const targetAttributeValue = anchorTarget.getAttribute('target'); + const opensInSameFrame = !targetAttributeValue || targetAttributeValue === '_self'; // Don't stop ctrl/meta-click (etc) from opening links in new tabs/windows - if (isWithinBaseUriSpace(absoluteHref) && !eventHasSpecialKey(event)) { + if (isWithinBaseUriSpace(absoluteHref) && !eventHasSpecialKey(event) && opensInSameFrame) { event.preventDefault(); performInternalNavigation(absoluteHref); } diff --git a/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs b/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs index 66360f85bae65a7433db62a794f9bd188ca36483..788feaf3941aee1392e18944722e69c06b87bbfa 100644 --- a/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs +++ b/test/Microsoft.AspNetCore.Blazor.E2ETest/Tests/RoutingTest.cs @@ -117,6 +117,34 @@ namespace Microsoft.AspNetCore.Blazor.E2ETest.Tests } } + [Fact] + public void CanFollowLinkToTargetBlankClick() + { + try + { + SetUrlViaPushState("/"); + + var app = MountTestComponent<TestRouter>(); + + app.FindElement(By.LinkText("Target (_blank)")).Click(); + + WaitAssert.Equal(2, () => Browser.WindowHandles.Count); + } + finally + { + // Closing newly opened windows if a new one was opened + while (Browser.WindowHandles.Count > 1) + { + Browser.SwitchTo().Window(Browser.WindowHandles.Last()); + Browser.Close(); + } + + // Needed otherwise Selenium tries to direct subsequent commands + // to the tab that has already been closed + Browser.SwitchTo().Window(Browser.WindowHandles.First()); + } + } + [Fact] public void CanFollowLinkToOtherPageDoesNotOpenNewWindow() { diff --git a/test/testapps/BasicTestApp/RouterTest/Links.cshtml b/test/testapps/BasicTestApp/RouterTest/Links.cshtml index 208f9d81cc614734048a3afccc94a19b7f40a441..f517de1a634f43f7c8cd42245e3359a492059759 100644 --- a/test/testapps/BasicTestApp/RouterTest/Links.cshtml +++ b/test/testapps/BasicTestApp/RouterTest/Links.cshtml @@ -20,3 +20,5 @@ <a id="anchor-with-no-href"> Anchor tag with no href attribute </a> + +<a href="/" target="_blank">Target (_blank)</a>