2012-08-22 22 views
7

Estoy tratando de abrir todos los enlaces externos en el sitio en una nueva ventana. Sin embargo, hay 2 versiones del sitio. por ejemplo, una tienda y el sitio principal. Entonces en el sitio principal podríamos tener enlaces que van a http://store.site.com por ejemplo.Abrir todos los enlaces externos abrir en una nueva pestaña aparte de un dominio

Tengo un código aquí que me permitirá abrir todos los enlaces externos en una nueva ventana. Sin embargo, me gustaría poder excluir ciertos dominios. Como el que he mencionado anteriormente.

Aquí está el código:

$(document).ready(function() { 
    $("a[href^=http]").each(function(){ 
     if(this.href.indexOf(location.hostname) == -1) { 
     $(this).attr({ 
      target: "_blank", 
      title: "Opens in a new window" 
     }); 
     } 
    }) 
}); 

Soy nuevo en JS/jQuery por lo tanto la información sería brillante.

Respuesta

11

Para activar los clics mediante programación, puede hacer algo como:

$(document).ready(function() { 

    $("a[href^=http]").each(function(){ 

     // NEW - excluded domains list 
     var excludes = [ 
     'excludeddomain1.com', 
     'excludeddomain2.com', 
     'excluded.subdomain.com' 
     ]; 
     for(i=0; i<excludes.length; i++) { 
     if(this.href.indexOf(excludes[i]) != -1) { 
      return true; // continue each() with next link 
     } 
     } 

     if(this.href.indexOf(location.hostname) == -1) { 

      // attach a do-nothing event handler to ensure we can 'trigger' a click on this link 
      $(this).click(function() { return true; }); 

      $(this).attr({ 
       target: "_blank", 
       title: "Opens in a new window" 
      }); 

      $(this).click(); // trigger it 
     } 
    }) 
}); 
+0

tecnología, gracias por la respuesta. Lo siento pero no veo qué es diferente aquí a lo que tengo en la parte superior de la página.¿Te importaría mostrarme dónde agrego el dominio que no creo que funcione como un dominio externo? –

+0

Editaré mi respuesta para reflejar que – techfoobar

+0

vea mis ediciones para la lógica de la lista de exclusión (solución simple). La respuesta original fue para señalar cómo puede activar por programación los clics del enlace (para abrirlos en una nueva pestaña) – techfoobar

1

¿Es capaz de editar el código HTML para obtener una mejor gancho para tal vez un evento de clic? Si necesito separar ciertos enlaces entre internos o externos, aplicaré un valor rel en el elemento HTML.

<a href="URL" rel="external">Link</a> 

Luego, en su Javascript

$('a[rel="external"]').click(function(event) { 
    event.stopPropagation(); 
    window.open($(this).attr('href')); 
    return false; 
    }); 

EDIT: ya que ya tiene un montón de enlaces, ¿qué tal esto ..

var a = new RegExp('http:\/\/store.blah.com'); 

    $('a').each(function() { 

     if(a.test(this.href)) { 
     $(this).click(function(event) { 
     event.preventDefault(); 
     event.stopPropagation(); 
     window.open(this.href, '_blank'); 
     }); 
     } 

    }); 
+0

Gracias por la respuesta. sí, tengo acceso al HTML, pero hay cientos de enlaces y, como se puede imaginar, puede llevar un tiempo. Sin embargo, voy a tomar nota de la forma en que lo ha hecho para futuras construcciones de sitios, así que gracias por eso. –

0

creo que lo haría como esto :

$(document).ready(function() { 
     $("a[href^=http]").each(function(){ 
     if(this.href.indexOf(location.hostname) == -1 && this.href.indexOf("store.domain.com") == -1 && this.href.indexOf("other.domain.rule") == -1) { 
      $(this).attr({ 
       target: "_blank", 
       title: "Opens in a new window" 
      }); 
     } 
     }) 
    }); 

Es un poco manual, pero, si no quiere lidiar con la división de cadenas y matrices, esta es la solución. Estoy seguro de que esto ayudará.

Editar: Y además de esto, puede utilizar la solución de techfoobar para activar los clics de enlace. Eso lo ayudará con el rendimiento de su sitio web.

+0

Agradable, muchas gracias. Parece que esto va a funcionar para mí. Se actualizará con respuesta en breve. –

0

En la misma línea que la respuesta de techfoobar, puede crear una lista de dominios que deben dejarse abiertos en la misma ventana. Puedes hacerlo de una manera más robusta aunque usando expresiones regulares. Si solo hace un indexOf directo(), se saltará los enlaces que tienen subdominios coincidentes pero no coinciden con los dominios, aunque puede omitir el '$' si desea hacer coincidir el nombre en cualquier lugar de la cadena href.

Esta implementación debe hacer lo que quiera y hay modificaciones mínimas al código que ha necesitado.

$(document).ready(function() { 
    //populate this list with whatever domain names you want, the 
    //$ sign matches the end of the string, only top level domains are affected 
    var whiteList = [/google.com\/$/, /stackoverflow.com\/$/]; 

    $("a[href^=http]").each(function(){ 
     if(this.href.indexOf(location.hostname) == -1) { 

     //check if the href of the current link matches any of our patterns 
     var href = this.href; 
     if(whiteList.filter(function(x){return x.test(href)}).length == 0) { 

     $(this).attr({ 
      target: "_blank", 
      title: "Opens in a new window" 
     }); 
     } 
     } 
    }) 
}); 

Con este ejemplo, todos los enlaces que van a google.com y stackoverflow.com también se abrirán en la página existente.

0

Si prefiere utilizar un controlador de eventos en el cuerpo que cambia el dom, recomiendo algo como esto ...

// open external links in a new tab 
    $('body').on('click','a',function(){ 
    var $a = $(this); 
    var href = $a.attr('href'); 
    if (href.indexOf('/') == 0) return; // ignore relative links 
    var target = $a.attr('target') || ""; 
    if (target.length > 0) return; // ignore links with a target attribute already 
    window.open(href, '_blank'); // open external links in a new tab 
    return false; 
    }); 
0

Esto va a hacer el truco para todos los dominios externos usando PHP

$(document).ready(function() { 
    $("a[href^=http]").each(function(){ 

     // NEW - excluded domains list 
     var excludes = [ 
     '<?php echo $_SERVER['HTTP_HOST']; ?>' 
     ]; 
     for(i=0; i<excludes.length; i++) { 
     if(this.href.indexOf(excludes[i]) != -1) { 
      return true; // continue each() with next link 
     } 
     } 

     if(this.href.indexOf(location.hostname) == -1) { 

      // attach a do-nothing event handler to ensure we can 'trigger' a click on this link 
      $(this).click(function() { return true; }); 

      $(this).attr({ 
       target: "_blank", 
       title: "Opens in a new window" 
      }); 

      $(this).click(); // trigger it 
     } 
    }) 
}); 
+0

simplemente reemplaza ese php con 'location.hostname' y ya no necesitas php – Uberfuzzy

Cuestiones relacionadas