Skip to content

Commit

Permalink
Ensure Skip link URL matches location.pathname
Browse files Browse the repository at this point in the history
  • Loading branch information
colinrotherham committed Dec 7, 2023
1 parent b58d909 commit 74e3a6c
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ export class SkipLink extends GOVUKFrontendComponent {
const linkedElementId = getFragmentFromUrl(hash)

// Check for link hash fragment
if (!linkedElementId) {
if (!linkedElementId || url.pathname !== window.location.pathname) {
throw new ElementError(
`Skip link: Target link (\`href="${href}"\`) has no hash fragment`
!linkedElementId
? `Skip link: Target link (\`href="${href}"\`) has no hash fragment`
: `Skip link: Target link (\`href="${href}"\`) must stay on page (\`${window.location.pathname}\`)`
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,5 +157,22 @@ describe('Skip Link', () => {
}
})
})

it('throws when the href links to another page', async () => {
await expect(
render(page, 'skip-link', {
context: {
text: 'Skip to main content',
href: '/somewhere-else#main-content'
}
})
).rejects.toMatchObject({
cause: {
name: 'ElementError',
message:
'Skip link: Target link (`href="/somewhere-else#main-content"`) must stay on page (`/components/skip-link/preview`)'
}
})
})
})
})

0 comments on commit 74e3a6c

Please sign in to comment.