Skip to content

Commit

Permalink
feat: External link must be opened in a new tab - MEED-6879 - Meeds-i…
Browse files Browse the repository at this point in the history
…o/MIPs#124 (#3809)

Before this change when we copy/paste an external link in the rich editor no target added to to link, so the link opened in the same tab.
This PR allows to add target _blank to external links to open in a new tab
  • Loading branch information
SaraBoutej authored May 21, 2024
1 parent a3b5ac2 commit 7e7d000
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
8 changes: 5 additions & 3 deletions webapp/portlet/src/main/webapp/js/ExtendedDomPurify.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,16 @@
ADD_ATTR: ['target', 'allow', 'allowfullscreen', 'frameborder', 'scrolling', 'v-identity-popover'],
});
DOMPurify.addHook('afterSanitizeAttributes', function(node) {
const nodeText = node.textContent;

if ('target' in node) {
// add noopener attribute to external links to eliminate vulnerabilities
node.setAttribute('rel', 'noopener');
// add text ellipsis when link length is up to 75 characters
const nodeText = node.textContent;
const nodeLink = node.getAttribute('href');
if (nodeText && nodeText.length > 75) {
node.setAttribute('title', nodeText);
node.setAttribute('Aria-label', nodeText);
node.setAttribute('title', nodeLink);
node.setAttribute('Aria-label', nodeLink);
node.textContent = node.textContent.substring(0,75)+'...';
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,23 @@ export default {
content = content.replace(/<oembed>(.*)<\/oembed>/g, '');
content = content.replace(/<oembed>(.*)<\/oembed>/g, `<oembed>${oembedUrl}</oembed>`);
}
if (content.includes('<a') && content.includes('</a>')) {
const tempdiv = document.createElement('div');
tempdiv.innerHTML = content;
const links = tempdiv.getElementsByTagName('a');
for (const link of links) {
if (link.href.indexOf(window.location.origin) === -1) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'nofollow noopener noreferrer');
}
if (link.text.length > 75) {
link.setAttribute('title', link.href);
link.setAttribute('Aria-label', link.href);
link.text = `${link.text.substring(0,75) }...`;
}
}
content = tempdiv.innerHTML;
}
content = content.replace(/<div><!\[CDATA\[(.*)]]><\/div>/g, '');
return content;
},
Expand Down

0 comments on commit 7e7d000

Please sign in to comment.