How can I make links open in a new tab

Hello people!
Currently, I need some help on a little something
You see, I need all links in my website, external and internal, to open in a new tab.
How can I do this?

I’ve looked in other topics and tried to apply what they said there, but still don’t manage to do so.
Maybe it doesn’t work in my ghost website, maybe I’m way too stupid
Could someone please explain to me how can I do this?

Can you tell what you’ve tried, and preferably link your actual site where it isn’t working?

I’ve tried to put these three bing AI generated codes on the ghost header, I’ve also tried putting them in the ghost footer, saved, and nothing happened.

these were the codes:

  • <script type=“text/javascript”> var links = document.querySelectorAll(‘a’); links.forEach((link) => { var a = new RegExp(‘/’ + window.location.host + ‘/’); if(!a.test(link.href)) { link.addEventListener(‘click’, (event) => { event.preventDefault(); event.stopPropagation(); window.open(link.href, ‘_blank’); }); } }); </script>
    * <script type=“text/javascript”> var links = document.getElementsByTagName(“a”); for (var i = 0; i < links.length; i++) { if (links[i].hostname != window.location.hostname) { links[i].target = ‘_blank’; } } </script>
  • <script type=“text/javascript”> var links = document.querySelectorAll(‘a’); links.forEach((link) => { if (link.href.includes(‘?xgtab&’)) { link.target = ‘_blank’; } }); </script>

Also, this code that I’ve seen in another forum question in this link: I want my external links to open in a new tab - Developer help - Ghost Forum

Which was this

<script type='text/javascript'>

$( document ).ready(function() {

$(".post-content a").attr("target","moredetail");

});

Then I tried this one

<script>
	var links = document.querySelectorAll('a');
	links.forEach((link) => {
		var a = new RegExp('/' + window.location.host + '/');
		if(link.href.indexOf("javascript") == -1){
			if(!a.test(link.href)) {
				link.addEventListener('click', (event) => {
					event.preventDefault();
					event.stopPropagation();
					window.open(link.href, '_blank');
				});
			}
		}
	});
</script>

Which works, but only for external links

But I need it to open both internal and external links on new tab
how can I do it?
my website is Panther Blog (pantherprotocol.io)

Update:
Slowly, I’ve come up with a code that does it for me
which is this one:

<script>
var links = document.querySelectorAll('a');
links.forEach((link) => {
  if (link.href.indexOf("javascript") == -1 && link.href != "https://blog.pantherprotocol.io/#/portal/signup") {
    // check if the link is not a javascript function and not the signup link
    link.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(link.href, '_blank');
    });
  }
});
</script>

and it works perfectly, but only with the previously loaded blog articles. When I scroll further into the page, it doesn’t work with the articles that weren’t previously loaded. How can I solve this?

Getting closer, sounds like! I suspect that the problem is that you have infinite scroll, but this code runs just once. So those later items don’t get modified. You could call it again after the new items load. The trick is doing that. That infinite scroll code is in casper.js. You could download the theme, edit the code (and then rebuild it, because it’s going to load the built form, not the human-readable form you find in assets/js).

But maybe we can avoid that. Try, at the end of the page (code injection footer)

function newOnScroll() {
// This is the original onScroll code
        lastScrollY = window.scrollY;
        requestTick();
// this is your existing code:
var links = document.querySelectorAll('a');
links.forEach((link) => {
  if (link.href.indexOf("javascript") == -1 && link.href != "https://blog.pantherprotocol.io/#/portal/signup") {
    // check if the link is not a javascript function and not the signup link
    link.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(link.href, '_blank');
    });
  }
});
}
$( document ).ready(function() {
// remove old eventlistener:
window.removeEventListener('scroll', onScroll); \\ removes existing eventlistener for scrolling.
// create the new eventlistener
window.addEventListener('scroll', newOnScroll, {passive: true}); // cause scrolling to trigger the new version.
});

Not tested, may work! :)

It didn’t work, but you sure did put me on the right track!
I’ve made this one:

<script>
// Code that makes every link in the website open in a new tab, including the ones that load with infinite scroll
// create a function that adds the click event listener to the links
function addClickListener(link) {
  if (link.href.indexOf("javascript") == -1 && link.href != "https://blog.pantherprotocol.io/#/portal/signup") {
    // check if the link is not a javascript function and not the signup link
    link.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(link.href, '_blank');
    });
  }
}

// get all the existing links on the page
var links = document.querySelectorAll('a');

// loop through them and add the click listener
links.forEach(addClickListener);

// create a MutationObserver to observe changes in the document
var observer = new MutationObserver((mutations) => {
  // loop through the mutations
  mutations.forEach((mutation) => {
    // check if new nodes were added
    if (mutation.addedNodes.length > 0) {
      // loop through the added nodes
      mutation.addedNodes.forEach((node) => {
        // check if the node is an element and has links inside
        if (node.nodeType === 1 && node.querySelectorAll('a').length > 0) {
          // get the links inside the node
          var newLinks = node.querySelectorAll('a');
          // loop through them and add the click listener
          newLinks.forEach(addClickListener);
        }
      });
    }
  });
});

// specify the target element and options for the observer
var target = document.body; // you can change this to a more specific element if you want
var options = {childList: true, subtree: true}; // observe child nodes and descendants

// start observing
observer.observe(target, options);
</script>

And it worked like a charm.

For whoever that comes across the same problem, here is a code without the personal tweaks for my blog (I adjusted it my own code so it made an expection to that so it doesn’t open a new tab in the subscribe button at the top of the page, this one don’t have the exception)

<script>
// Code that makes every link in the website open in a new tab, including the ones that load with infinite scroll
// create a function that adds the click event listener to the links
function addClickListener(link) {
  if (link.href.indexOf("javascript") == -1) {
    // check if the link is not a javascript function
    link.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(link.href, '_blank');
    });
  }
}

// get all the existing links on the page
var links = document.querySelectorAll('a');

// loop through them and add the click listener
links.forEach(addClickListener);

// create a MutationObserver to observe changes in the document
var observer = new MutationObserver((mutations) => {
  // loop through the mutations
  mutations.forEach((mutation) => {
    // check if new nodes were added
    if (mutation.addedNodes.length > 0) {
      // loop through the added nodes
      mutation.addedNodes.forEach((node) => {
        // check if the node is an element and has links inside
        if (node.nodeType === 1 && node.querySelectorAll('a').length > 0) {
          // get the links inside the node
          var newLinks = node.querySelectorAll('a');
          // loop through them and add the click listener
          newLinks.forEach(addClickListener);
        }
      });
    }
  });
});

// specify the target element and options for the observer
var target = document.body; // you can change this to a more specific element if you want
var options = {childList: true, subtree: true}; // observe child nodes and descendants

// start observing
observer.observe(target, options);
</script>

Cathy, you think that this code may be somehow bad for my website’s performance?

2 Likes

This script opens links in new tabs from /posts - class: .l-post-content a
You can modify this accordingly to open links in particular section like only in /pages and /posts

  • working!
<script>
  var links = document.querySelectorAll('.l-post-content a'); // Select only links within elements with the class .l-post-content 
  links.forEach((link) => {
    link.addEventListener('click', (event) => {
      event.preventDefault();
      event.stopPropagation();
      window.open(link.href, '_blank');
    });
  });
</script>

I think that this blog post might help you with opening links in a new window in Ghost - we have covered most of the cases that you might need.

1 Like