Skip to content

Commit 15655b4

Browse files
authored
merge(#3): from richardneililagan/master
Fixes: [rel=noreferrer] is not added when element has no existing [rel]
2 parents 555e4bf + ee50080 commit 15655b4

File tree

3 files changed

+38
-14
lines changed

3 files changed

+38
-14
lines changed

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/index.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,19 +28,19 @@ export function posthtmlExternalLink(
2828
}
2929
}
3030

31-
if (node.attrs.rel) {
32-
const rels = new Set(node.attrs.rel.split(/\s+/));
33-
rels.add('noopener');
34-
rels.add('nofollow');
35-
rels.add('external');
36-
if (config.noreferrer) {
37-
rels.add('noreferrer');
38-
}
39-
40-
node.attrs.rel = Array.from(rels).join(' ');
41-
} else {
42-
node.attrs.rel = 'noopener nofollow external';
43-
}
31+
// :: append rels to the element's [rel] value.
32+
// failsafes in case [rel] is not defined yet.
33+
const rels = node.attrs.rel
34+
? new Set(node.attrs.rel.split(/\s+/))
35+
: new Set();
36+
37+
// config.noreferrer && rels.add('noreferrer');
38+
if (config.noreferrer) rels.add('noreferrer');
39+
rels.add('noopener');
40+
rels.add('nofollow');
41+
rels.add('external');
42+
43+
node.attrs.rel = Array.from(rels).join(' ');
4444

4545
node.attrs.target = '_blank';
4646
}

test/test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,30 @@ describe('posthtml-external-link', () => {
7878
result.should.include('" target="_blank"');
7979
});
8080

81+
it('adds noreferrer when config is set', async () => {
82+
const parser = posthtml([plugin({
83+
exclude: ['skk.moe'],
84+
noreferrer: true
85+
})]);
86+
87+
const input = '<a href="https://example.com" rel="example">Example</a>';
88+
const { html: result } = await parser.process(input);
89+
90+
result.should.include(' rel="example noreferrer noopener nofollow external"');
91+
});
92+
93+
it('adds noreferrer even to elements without an existing [rel]', async () => {
94+
const parser = posthtml([plugin({
95+
exclude: ['skk.moe'],
96+
noreferrer: true
97+
})]);
98+
99+
const input = '<a href="https://example.com">Example</a>';
100+
const { html: result } = await parser.process(input);
101+
102+
result.should.include(' rel="noreferrer noopener nofollow external"');
103+
});
104+
81105
it('target attr', async () => {
82106
const { html: result } = await posthtml([plugin({ exclude: ['skk.moe'] })]).process('<a href="https://example.com/" target="_self">Example</a>');
83107

0 commit comments

Comments
 (0)