Mi sitio web tiene toneladas de URL internas y externas.
para mi nombre de host o "#" href , debería abrirse en la misma pestaña, pero para cualquier otro dominio, mi nombre de host debería estar abierto en una nueva pestaña.
Este código hace que todas las URL se abran en una nueva pestaña, incluidos los enlaces internos.
<base target="_blank" rel="noopener noreferrer">También probé ( https://stackoverflow.com/a/12071371 )
$(document).ready(function() { $('a[href^="https://"],a[href^="http://"]').each(function(){ // NEW - excluded domains list var excludes = [ 'google.com', 'www.example.com', '*.example.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", rel: "noreferrer nofollow noopener", title: "Opens in a new window" }); $(this).click(); // trigger it } }) });Proporcione la solución en HTML, javascript o PHP.
Con javascript, puede recorrer todos los enlaces y agregar target="_blank" a cualquier enlace que no coincida con el dominio actual:
window.addEventListener("DOMContentLoaded", e => { document.querySelectorAll('a[href]').forEach(a => { if (location.hostname == new URL(a.href).hostname) return; a.target = "_blank"; a.rel = "noreferrer nofollow noopener"; }); }); .content { height: 100vh; } <div class="content"> <a href="/">internal link</a> <a href="#test">internal link 2</a> <a href="https://stackoverflow.com">external link</a> <a href="http://stackoverflow.com">external link 2</a> </div> <div id="test" class="content">blah</div>Puede recorrer todos los elementos a y verificar si su href contiene http:// o https:// y, de ser así, establecer target="_blank" en el enlace:
document.querySelectorAll("a").forEach(function(element){ let href = element.getAttribute("href"); // Check to see if the the href include http:// or https:// if(href.includes("http://") || href.includes("https://")){ element.target = "_blank"; // Make link open in new tab element.rel = "noreferrer nofollow noopener"; } console.log(element); // Just for testing }); <a href="foo.html">Link</a><br> <a href="http://foo.html">Link</a><br> <a href="foo.html">Link</a><br> <a href="https://foo.html">Link</a>intente agregar una etiqueta 'a' dentro de la etiqueta con el enlace y target="_blank" dentro de la etiqueta 'a'