Skip to content

TCA-355 Open External Links in New Window -> dev #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 24, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions client/src/components/layouts/tc-integration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ class TcIntegrationLayout extends Component<TcIntegrationLayoutProps> {

window.addEventListener('online', this.updateOnlineStatus);
window.addEventListener('offline', this.updateOnlineStatus);
window.addEventListener('click', this.externalLinkHandler);
}

componentDidUpdate(prevProps: TcIntegrationLayoutProps) {
Expand All @@ -112,6 +113,41 @@ class TcIntegrationLayout extends Component<TcIntegrationLayoutProps> {
window.removeEventListener('offline', this.updateOnlineStatus);
}

externalLinkHandler = (event: MouseEvent) => {
// prettier is the worst

// if we're not clicking an anchor tag, there's nothing to do
const eventTarget = event.target as HTMLElement;
if (eventTarget?.localName !== 'a') {
return;
}

// if the target of the click isn't external, there's nothing to do
const target = eventTarget as HTMLAnchorElement;
const url = new URL(target.href);
if (url.host === window.location.host) {
return;
}

// stop the click so we can alter it
event.stopPropagation();
event.preventDefault();

// if this is a freecodecamp lesson, change its domain and path
if (url.host === 'learn.freecodecamp.org') {
url.host = window.location.host;
// TODO: it would be nice to not require that the FCC
// app knows about the paths in the platform UI, but
// creating a way to share this info would be complex and
// time consuming, so we can handle it when we get another
// provider.
url.pathname = `learn/freecodecamp/${url.pathname}`;
}

// now open the url in a new tab
window.open(url, '_blank');
};

updateOnlineStatus = () => {
const { onlineStatusChange } = this.props;
const isOnline =
Expand Down