Skip to content

Commit

Permalink
capricorn86#1176@patch: Prevent custom element redefinition.
Browse files Browse the repository at this point in the history
  • Loading branch information
mash-graz committed Dec 10, 2023
1 parent 8f3bbe1 commit 1997a86
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ export default class CustomElementRegistry {
);
}

if (this._registry[localName]) {
throw new DOMException(`Custom Element: "${localName}" already defined.`);
}

this._registry[localName] = {
elementClass,
extends: options && options.extends ? options.extends.toLowerCase() : null
Expand Down Expand Up @@ -124,7 +128,7 @@ export default class CustomElementRegistry {
* Reverse lookup searching for tagName by given element class.
*
* @param elementClass Class constructor.
* @returns First found Tag name or `null`.
* @returns Found Tag name or `null`.
*/
public getName(elementClass: typeof HTMLElement): string | null {
const localName = Object.keys(this._registry).find(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ describe('CustomElementRegistry', () => {
);
});

it('Throws an error if already defined.', () => {
customElements.define('custom-element', CustomElement);
expect(() => customElements.define('custom-element', CustomElement)).toThrow();
});

it('Calls observed attributes and set _observedAttributes as a property on the element class.', () => {
customElements.define('custom-element', CustomElement);
expect(CustomElement.observedAttributesCallCount).toBe(1);
Expand Down Expand Up @@ -87,9 +92,9 @@ describe('CustomElementRegistry', () => {
});

describe('whenDefined()', () => {
it('Throws an error if tag name looks invalide', async () => {
it('Throws an error if tag name looks invalid.', async () => {
const tagName = 'element';
expect(async() => await customElements.whenDefined(tagName)).rejects.toThrow();
expect(async () => await customElements.whenDefined(tagName)).rejects.toThrow();
});

it('Returns a promise which is fulfilled when an element is defined.', async () => {
Expand Down Expand Up @@ -119,12 +124,12 @@ describe('CustomElementRegistry', () => {
});

describe('createElement()', () => {
it('Case insensitive access via document.createElement()', () => {
it('Case insensitive access via document.createElement().', () => {
customElements.define('custom-element', CustomElement);
expect(document.createElement('CUSTOM-ELEMENT').localName).toBe('custom-element');
});

it('Non-ASCII capital letters in document.createElement()', () => {
it('Non-ASCII capital letters in document.createElement().', () => {
customElements.define('a-Öa', CustomElement);
expect(document.createElement('a-Öa').localName).toMatch(/a-Öa/i);
});
Expand Down

0 comments on commit 1997a86

Please sign in to comment.