Streaming live at 10am (PST)

Making links always "open in new tab"

Hiya

Does anyone know how to make it so that all external links automatically open in a new tab?
I’m happy for all links to be this way, or ideally internal ones just open in the current tab.
Is there a way to do this that doesn’t require me to tick the box every time?

Many thanks
Bradley


Here is my site Read-Only: LINK
(how to share your site Read-Only link)

1 Like

I’ve never tried this myself, but I got this idea:

Get JavaScript to change the Attribute for every <a> tag.

jQuery Set Attribute: $( *selector* ).attr( *attribute,value* )
Attribute for the <a> tag: target="_blank"

$( document ).ready(function() {
    $( "a" ).attr( target, _blank );
});

Please let me know if it works

1 Like

Pretty usefull ! Thanks for sharing @Jeandcc :slight_smile:

1 Like

I really hope it helps.

I’m coming up with some interesting stuff for someone that pretty much just learned jQuery haha.

I think the idea was good, had a similar one with vanilla javascript but it does not work. It looks a tiny bit more complicated, here is the solution I found and pimped up a bit:

Vanilla Javascript

<script>
function externalLinks() {
  let arrayOfLinks = document.getElementsByTagName("a");
  for (i = 0; i < arrayOfLinks.length; i++) {
    let link = arrayOfLinks[i];
    link.getAttribute("href") &&
      link.hostname !== location.hostname &&
      (link.target = "_blank");
  }
}
externalLinks();
</script>

jQuery

<script>
jQuery(document.links)
  .filter(function() {
    return this.hostname != window.location.hostname;
  })
  .attr("target", "_blank");
</script>

Source:

I tested it out and it works :slight_smile:

3 Likes

I’m glad to know that mine works! And wow, that one is really big huh? hahaha

no, your script actually does not work :wink: I did try your idea but it opens links within the same tab unfortunately. The above scripts appear to be the only way to go.

EDIT:
The magic happens within the location.hostname parameter

Oh, got ya. Well, I still have a lot to learn hahha

1 Like

We all do ! :nerd_face:

I’ve learned something new today too… I made a codepen with some extra explanations… maybe easier to read in codepen than here on Webflow forum.

Codepen:
https://codepen.io/anthonysalamin/pen/QPGbWm?editors=1010

Webflow:
here is the read-only link of the Webflow implementation

Hope that helps !

1 Like

I have read an interesting article regarding links being opened with target=“_blank” It appears we should add another attribute called “noopener” which prevents attack surface vulnerabilities.

Updated codepen:
https://codepen.io/anthonysalamin/pen/QPGbWm

Source:

1 Like

Thanks!! I’ll definitely look into it

Sorry I never replied to this, I hadn’t even realised a discussion took place!
Thank you so much!
I will give the code a try.
Is it possible to make it so that only external links open in new tab?