Skip to content

Commit

Permalink
fix: Opens foreign links from article page in new tab [cw-2725] (#8304)
Browse files Browse the repository at this point in the history
Co-authored-by: Sivin Varghese <64252451+iamsivin@users.noreply.github.com>
  • Loading branch information
nithindavid and iamsivin committed Nov 21, 2023
1 parent e750ee6 commit 31c709b
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
39 changes: 39 additions & 0 deletions app/javascript/portal/portalHelpers.js
Expand Up @@ -68,6 +68,44 @@ export const updateThemeStyles = theme => {
setPortalClass(theme);
};

export const openExternalLinksInNewTab = () => {
const { customDomain, hostURL } = window.portalConfig;
const isSameHost =
window.location.href.includes(customDomain) ||
window.location.href.includes(hostURL);

// Modify external links only on articles page
const isOnArticlePage =
isSameHost && document.querySelector('#cw-article-content') !== null;

document.addEventListener('click', function (event) {
if (!isOnArticlePage) return;

// Some of the links come wrapped in strong tag through prosemirror

const isTagAnchor = event.target.tagName === 'A';
const isParentTagAnchor =
event.target.tagName === 'STRONG' &&
event.target.parentNode.tagName === 'A';

if (isTagAnchor || isParentTagAnchor) {
const link = isTagAnchor ? event.target : event.target.parentNode;

const isInternalLink =
link.hostname === window.location.hostname ||
link.href.includes(customDomain) ||
link.href.includes(hostURL);

if (!isInternalLink) {
link.target = '_blank';
link.rel = 'noopener noreferrer'; // Security and performance benefits
// Prevent default if you want to stop the link from opening in the current tab
event.stopPropagation();
}
}
});
};

export const toggleAppearanceDropdown = () => {
const dropdown = document.getElementById('appearance-dropdown');
if (!dropdown) return;
Expand Down Expand Up @@ -183,6 +221,7 @@ export const InitializationHelpers = {
},

initialize: () => {
openExternalLinksInNewTab();
if (window.portalConfig.isPlainLayoutEnabled === 'true') {
InitializationHelpers.appendPlainParamToURLs();
} else {
Expand Down
2 changes: 2 additions & 0 deletions app/views/layouts/portal.html.erb
Expand Up @@ -50,6 +50,8 @@ By default, it renders:
window.portalConfig = {
portalSlug: '<%= @portal.slug %>',
portalColor: '<%= @portal.color %>',
customDomain: '<%= @portal.custom_domain %>',
hostURL: '<%= ENV.fetch('FRONTEND_URL', '') %>',
theme: '<%= @theme %>',
localeCode: '<%= @locale %>',
searchTranslations: {
Expand Down

0 comments on commit 31c709b

Please sign in to comment.