Is there a way to confirm if a link is within the same domain before opening it in the current tab?

I am currently working on an Angular 8 application.

In this application, there is a specific requirement for handling links. For external links, such as www.ad.nl, clicking on them should open in a new tab.

However, if the link belongs to the same domain as the website (e.g., localhost: http://localhost:4200/gezondheid/Measurement/actieindex), it should load in the same tab instead of opening a new one.

To achieve this functionality, I have created a function for external links:

@Input() activities: Activity[];

 isExternalLink(link: string): boolean {
    const currentHost = window.location.hostname;
    const linkHost = link.replace(/^http?:\/\/([^\/]*)\/.*/, (match, g1) => g1);
    return currentHost !== linkHost;
  }

  getRouterLink(link: string): string {
    return '/' + link;
  }

Below is the template code that implements this logic:

  <a
      *ngIf="activity.link; else nolink"
      [href]="activity.link"
      [attr.target]="isExternalLink(activity.link) ? '_blank' : null"
      [attr.rel]="isExternalLink(activity.link) ? 'noopener noreferrer' : null"
    >

Currently, the issue arises when a link from the same domain is clicked, like http://localhost:4200/gezondheid/Measurement/actieindex, as it opens in a separate tab.

Answer №1

Here's a simple function that can help determine if a link is an external one:

isExternalLink(link: string): boolean {
    const currentHost = window.location.hostname;
    return !linkHost.includes(currentHost);
  }

For instance, when on this page (Stack Overflow), window.location.hostname will yield "stackoverflow.com". If you have a link like "", the method would output false. Conversely, let's consider "https://www.google.com/search?q=javascript&oq=javascript&aqs=chrome..69i57j69i60l3.2657j0j1&sourceid=chrome&ie=UTF-8", in this case it would output true.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with reading d3.js visualization data from a JSON file

I am currently working on a data visualization project using D3.js and I started with a basic framework that I found on this link The data for my visualization is coming from a json file containing only two values, a string value and an integer. However, ...

Is it possible to use a Jasmine spy on a fresh instance?

In need of assistance with testing a TypeScript method (eventually testing the actual JavaScript) that I'm having trouble with. The method is quite straightforward: private static myMethod(foo: IFoo): void { let anInterestingThing = new Interesti ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

What is the reason why the swiper feature is malfunctioning in my React-Vite-TS application?

I encountered an issue when trying to implement Swiper in my React-TS project. The error message reads as follows: SyntaxError: The requested module '/node_modules/.vite/deps/swiper.js?t=1708357087313&v=044557b7' does not provide an export na ...

Tips for implementing validations on a table that changes dynamically

I encountered an issue in my code while working on a dynamic form for age with unobtrusive client-side validation. The problem is that the validation is row-wise, but it behaves incorrectly by removing other rows' validations when I change one. Below ...

Guidelines for attaining seamless motion animation utilizing devicemotion rotationRate information

I am utilizing the rotationRate data obtained from the devicemotion eventListener to manipulate a three.js scene by tilting. The scene does respond to the data accurately in terms of angle adjustments, but it produces an unsmooth motion effect. Is there a ...

Enable form submission using the ENTER key when the focus is outside of an input field

Within my form, I have a div element that is focusable using tabindex="0". While this setup works well overall, I am facing an issue with submitting the form using the enter key. The submission works when an input field is in focus but not when the div has ...

Error Handling in ReactJS

Every time I try to execute my ReactJS code, an error pops up saying: Unhandled Rejection (Error): Material-UI: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e2f5f1f3e4d0a1a6bea3bea0">[email protected]</a> ve ...

Troubleshooting data binding issues in Angular.js using Jade and Express

I've been diving into AngularJS using Dan Wahlin's tutorial (http://youtu.be/i9MHigUZKEM?t=13m35s). In my views/index.jade file, I've implemented the code below: !!! 5 html(data-ng-app='') head title Angular Tutorial body ...

Caution in React: Utilizing functions with Object.assign() may not be a valid approach when dealing with React children

I have a setup using react for front-end and node for back-end. My goal is to retrieve data from the server to update the user entries on the front-end. I came across using Object.assign() as a potential solution to re-render user entries, but encountered ...

Storing response data as a variable in TypeScript with Angular 2 can be achieved by declaring a variable

I am unfamiliar with TypeScript and need assistance. After performing a POST request, I received an _id that I now need to use to execute a PUT function for play pause. When the play pause button is clicked, the response should be sent to the server. Below ...

Is there a way to optimize app speed in Angular2 by importing CommonModule and RouterModule in a centralized location?

I find myself constantly importing these two modules in almost every component: import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; Is there a way to import them only once in the global app. ...

Crack encrypted information using Typescript after it was encoded in Python

I've encountered an issue while attempting to decrypt previously encrypted data in Python. Here is how I encrypt the data in Python: iv = Random.new().read( AES.block_size ) cipher = AES.new(secret_key, AES.MODE_CBC, iv) encrypdata = base64.b64enco ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

Unlinked from the main content, the Angular2 Material2 sidenav stands on its

I am in the process of implementing the material2 sidenav component. My goal is to have a standalone, full-height sidebar that smoothly slides in and out without any interference with the rest of the app layout caused by the sidenav-layout. The desired ou ...

Tips for transforming C#.NET code into JavaScript code

A few years back (around 3 or 4 years ago), I recall hearing about a fascinating concept that involved generating client-side JavaScript code from C#.NET source code. It may have been related to validation tasks specifically... Does anyone have more inform ...

Techniques for looping through a PHP array using JavaScript

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Attendance Manager - Home</title> ...

The JavaScript and CSS properties are not functioning properly with the HTML text field

I came across this CodePen example by dsholmes and made some modifications: Here Furthermore, I have developed my own form on another CodePen pen: Link The issue I'm facing is related to the placeholders/labels not disappearing when typing in text f ...

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...

Every time I use Axios with NextJS, I keep getting a frustrating 405 method not allowed

I am facing a challenging issue with this... Currently, I am using NextJS for the frontend and making a request to <frontend-domain>/api/auth/register from here. const changePassword = async (currentPassword, password) => { await axios.post(& ...