fix(platform-browser): in Meta.addTag() do not add duplicate meta tags (#42703)

Previously, if there were two tags with the same "name" or "property" attribute selector,
then only the first was checked for duplicates when deciding whether to add a new meta
tag.

Fixes #42700
Fixes #19606

PR Close #42703
This commit is contained in:
Pete Bacon Darwin 2021-06-29 17:30:12 +01:00 committed by Jessica Janiuk
parent f3965ff834
commit 234b5edcc7
2 changed files with 12 additions and 2 deletions

View File

@ -166,11 +166,11 @@ export class Meta {
HTMLMetaElement { HTMLMetaElement {
if (!forceCreation) { if (!forceCreation) {
const selector: string = this._parseSelector(meta); const selector: string = this._parseSelector(meta);
const elem: HTMLMetaElement = this.getTag(selector)!;
// It's allowed to have multiple elements with the same name so it's not enough to // It's allowed to have multiple elements with the same name so it's not enough to
// just check that element with the same name already present on the page. We also need to // just check that element with the same name already present on the page. We also need to
// check if element has tag attributes // check if element has tag attributes
if (elem && this._containsAttributes(meta, elem)) return elem; const elem = this.getTags(selector).filter(elem => this._containsAttributes(meta, elem))[0];
if (elem !== undefined) return elem;
} }
const element: HTMLMetaElement = this._dom.createElement('meta') as HTMLMetaElement; const element: HTMLMetaElement = this._dom.createElement('meta') as HTMLMetaElement;
this._setMetaElementAttributes(meta, element); this._setMetaElementAttributes(meta, element);

View File

@ -167,6 +167,16 @@ import {expect} from '@angular/platform-browser/testing/src/matchers';
expect(metaService.getTags(selector).length).toEqual(1); expect(metaService.getTags(selector).length).toEqual(1);
}); });
it('should not add meta tag if it is already present on the page, even if the first tag with the same name has different other attributes',
() => {
metaService.addTag({name: 'description', content: 'aaa'});
metaService.addTag({name: 'description', content: 'bbb'});
metaService.addTag({name: 'description', content: 'aaa'});
metaService.addTag({name: 'description', content: 'bbb'});
expect(metaService.getTags('name="description"').length).toEqual(2);
});
it('should add meta tag if it is already present on the page and but has different attr', it('should add meta tag if it is already present on the page and but has different attr',
() => { () => {
const selector = 'property="fb:app_id"'; const selector = 'property="fb:app_id"';