Skip to content

Commit

Permalink
Check Skip link URL and return early for external URLs
Browse files Browse the repository at this point in the history
We don’t need to proceed with event listeners and focus handling if the target isn’t on the same page

For example, Exit this page secondary link

https://design-system.service.gov.uk/components/exit-this-page/#adding-the-secondary-link
  • Loading branch information
colinrotherham committed Dec 7, 2023
1 parent e2163d3 commit 4e5cb52
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ export class SkipLink extends GOVUKFrontendComponent {

const hash = this.$module.hash
const href = this.$module.getAttribute('href') ?? ''
const url = new window.URL(this.$module.href)

// Check for external link URL and return early
if (url.origin !== window.location.origin) {
return
}

const linkedElementId = getFragmentFromUrl(hash)

Expand Down Expand Up @@ -73,6 +79,10 @@ export class SkipLink extends GOVUKFrontendComponent {
* @private
*/
focusLinkedElement() {
if (!this.$linkedElement) {
return
}

if (!this.$linkedElement.getAttribute('tabindex')) {
// Set the element tabindex to -1 so it can be focused with JavaScript.
this.$linkedElement.setAttribute('tabindex', '-1')
Expand Down Expand Up @@ -101,6 +111,10 @@ export class SkipLink extends GOVUKFrontendComponent {
* @private
*/
removeFocusProperties() {
if (!this.$linkedElement) {
return
}

this.$linkedElement.removeAttribute('tabindex')
this.$linkedElement.classList.remove('govuk-skip-link-focused-element')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ describe('Skip Link', () => {
})

describe('errors at instantiation', () => {
it('can return early without errors for external href', async () => {
await render(page, 'skip-link', {
context: {
text: 'Exit this page',
href: 'https://www.bbc.co.uk/weather'
}
})
})

it('can throw a SupportError if appropriate', async () => {
await expect(
render(page, 'skip-link', examples.default, {
Expand Down

0 comments on commit 4e5cb52

Please sign in to comment.