Skip to content

Commit 01aad1e

Browse files
committed
Fix invalid hash error
Resolves #499
1 parent e346f5a commit 01aad1e

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

src/router-component.ts

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -118,14 +118,22 @@ export class RouterComponent extends HTMLElement {
118118
'hash-scroll-behavior'
119119
) as ScrollBehavior;
120120
const hashId = hash.replace('#', '');
121-
const hashElement = querySelectorDeep(
122-
`[id=${hashId}]`,
123-
this
124-
) as HTMLElement;
125-
if (hashElement) {
126-
hashElement.scrollIntoView({
127-
behavior: behaviorAttribute || 'auto',
128-
});
121+
try {
122+
const hashElement = querySelectorDeep(
123+
`[id=${hashId}]`,
124+
this
125+
) as HTMLElement;
126+
if (hashElement) {
127+
hashElement.scrollIntoView({
128+
behavior: behaviorAttribute || 'auto',
129+
});
130+
}
131+
} catch (e) {
132+
// id attributes can only have valid characters, if invalid, skip
133+
console.warn(
134+
`Cannot scroll to element with the id of "${hashId}".`
135+
);
136+
return;
129137
}
130138
}
131139

tests/router-component-tests.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,17 @@ describe('<router-component>', async () => {
491491
});
492492
});
493493

494+
it('warns when hash passed to querySelectorDeep throws because there is no matching element', async () => {
495+
const hash = 'test';
496+
querySelectorDeep.throws('error');
497+
window.history.pushState({}, document.title, `/page1#${hash}`);
498+
const popstate = new PopStateEvent('popstate', { state: {} });
499+
window.dispatchEvent(popstate);
500+
expect(consoleWarn).to.be.calledWithExactly(
501+
`Cannot scroll to element with the id of "${hash}".`
502+
);
503+
});
504+
494505
it('scrolls back to top of page if there is no hash', async () => {
495506
window.history.pushState({}, document.title, '/page1');
496507
const popstate = new PopStateEvent('popstate', { state: {} });

0 commit comments

Comments
 (0)