1

I use the following code so everything opens in the web app:

<script type="text/javascript">
var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
{
   a[i].onclick=function()
   {
       window.location=this.getAttribute("href");
       return false
   }
}

However, even on desktop, links that have target="_blank", still open in the same tab. How can I make all external links open in a new tab, while still keeping all internal links in the same tab. I've found solutions for single links, but I have too many to change by hand.

Note: I'm on apache so a config file change would also work.

Capsule
  • 6,118
  • 1
  • 20
  • 27
NerdOfLinux
  • 1,017
  • 10
  • 24

2 Answers2

2

If you set the "target" attribute on the links they will open in a new tab:

<script>
var origin=window.location.origin;
var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
{
   var link = a[i];
   if(link.href && link.href.indexOf(origin)!=0)
    link.setAttribute("target", "_blank");
}
</script>

In WordPress admin you can go to Theme editor and put this code in your footer.

Alexander Higgins
  • 6,765
  • 1
  • 23
  • 41
1

I managed to find an answer from this post. I just put this in my header:

<script>
// Mobile Safari in standalone mode
if(("standalone" in window.navigator) && window.navigator.standalone){

    // If you want to prevent remote links in standalone web apps opening Mobile Safari, change 'remotes' to true
    var noddy, remotes = false;

    document.addEventListener('click', function(event) {

        noddy = event.target;

        // Bubble up until we hit link or top HTML element. Warning: BODY element is not compulsory so better to stop on HTML
        while(noddy.nodeName !== "A" && noddy.nodeName !== "HTML") {
            noddy = noddy.parentNode;
        }

        if('href' in noddy && noddy.href.indexOf('http') !== -1 && (noddy.href.indexOf(document.location.host) !== -1 || remotes))
        {
            event.preventDefault();
            document.location.href = noddy.href;
        }

    },false);
}
</script>

and all normal links open within the web app, but on mobile and desktop, links with target="_blank" open in a new tab.

NerdOfLinux
  • 1,017
  • 10
  • 24