简体   繁体   English

如何仅自动将 target="_blank" 添加到外部链接?

[英]How to automatically add target=“_blank” to external links only?

I'm building a custom, industry-specific cms (using django).我正在构建一个自定义的、特定于行业的 cms(使用 django)。 In the backend, webmasters can specify either an internal link, eg "/page1" or an external link to use for various navigation elements throughout the website (all use <a> when rendered) .在后端,网站管理员可以指定内部链接,例如“/page1”或外部链接以用于整个网站的各种导航元素(在呈现时均使用<a> )。 The problem is that I would like internal links to open in the current tab, but external links should use target="_blank" to open a new tab or window.问题是我希望在当前选项卡中打开内部链接,但外部链接应该使用target="_blank"打开一个新选项卡或窗口。

How can I process the html to accomplish this?如何处理 html 以完成此操作?

I'd prefer a server-side solution, but am not aware of any clean way to pre-process rendered templates in django.我更喜欢服务器端解决方案,但我不知道在 Django 中预处理渲染模板的任何干净方法。 So, I assume the most straightforward way to do this is probably a javascript/jquery solution: a script that runs when each page loads, which adds the target="_blank" attribute to all external links but not internal links.因此,我认为最直接的方法可能是 javascript/jquery 解决方案:在每个页面加载时运行的脚本,它将 target="_blank" 属性添加到所有外部链接,但不添加内部链接。 But I'm not sure how to do this, either.但我也不知道该怎么做。

I've been using the following for awhile.我已经使用以下一段时间了。 Can't remember where I found it originally:不记得我最初在哪里找到它:

$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
           && (obj.hostname != location.hostname)
           && !obj.href.match(/^javascript\:/)
           && !obj.href.match(/^$/)
};

That adds an :external jQuery selector, so then you can just do:这添加了一个:external jQuery 选择器,所以你可以这样做:

$('a:external').attr('target', '_blank');

The nice part about using the custom selector, is that if you need to modify what contitutes an "external" link, you can change it in one place and not worry about the rest of your code.使用自定义选择器的好处在于,如果您需要修改构成“外部”链接的内容,您可以在一个地方更改它,而不必担心其余代码。 For instance in my organization, we have certain subdomains that aren't "external", but that we still want to open in new windows.例如,在我的组织中,我们有某些不是“外部”的子域,但我们仍想在新窗口中打开它们。

Try something like尝试类似的东西

for (var links = document.links, i = 0, a; a = links[i]; i++) {
        if (a.host !== location.host) {
                a.target = '_blank';
        }
}

Don't forget to run the script by the time all links exist in the document tree - in window.onload event.不要忘记在文档树中存在所有链接时运行脚本 - 在window.onload事件中。

You could do something like this:你可以这样做:

$(document.body).on('mouseover', 'a[target!=_blank]:not(.local)', function (evt) {
    var a = $(this);
    var href = a.attr('href');
    var domain = href.match(/^https?:\/\/([^:\/]+)/);
    if (domain && domain[1] && domain[1] !== "yourdomain.com") {
        a.attr('target', '_blank');
    } else {
        a.addClass('local');
    }
});

This will process each link as you click it, and shouldn't process each link more than once.这将在您单击每个链接时对其进行处理,并且不应多次处理每个链接。 If it needs to be external, the target will be set to _blank and it should open in a new window.如果它需要是外部的, target将被设置为_blank并且它应该在一个新窗口中打开。 Here's a working jsfiddle .这是一个有效的 jsfiddle

Update : My method of determining if the link stays on-site or not is quite crude.更新:我确定链接是否保留在现场的方法非常粗糙。 The method in this answer is more thorough.这个答案中的方法更彻底。 I would probably replace my simple regex match with that test instead.我可能会用该测试替换我的简单正则表达式匹配。

I recommend you do that server side.我建议你做那个服务器端。 Modify the template of the page depending on the locality of the link.根据链接的位置修改页面的模板。

As the great accepted answer from @Chris Pratt does not work for eg tel: links and other special cases I just use the following variant in order to not touch special links:由于@Chris Pratt 的公认答案不适用于例如 tel: links 和其他特殊情况,因此我仅使用以下变体来避免接触特殊链接:

(function($) {

    $.expr[':'].external = function(obj){
        return (obj.hostname != location.hostname) && obj.href.startsWith("http");
    };

    $('a:external').attr('target', '_blank');

}) (jQuery);

You could also do this:你也可以这样做:

$("a[href^='http://']").attr("target","_blank");

or要么

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

Slight change in code, which doesn't give errors, additional = in !==代码略有变化,不会出错,附加 = in !==

$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/) && (obj.hostname !== location.hostname) && !obj.href.match(/^javascript\:/) && !obj.href.match(/^$/);
};
$('a:external').attr('target', '_blank');

Another JavaScript solution:另一个 JavaScript 解决方案:

(() => {
  (document.querySelectorAll('a')).forEach(link => {
    link.hostname !== location.hostname && link.setAttribute('target', '_blank');
  })
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用javascript仅将target =“ _ blank”添加到某些链接? - How to use javascript to add target=“_blank” to some links only? 如何为目标=“ _ blank”的外部链接确定引荐来源网址? - How to determine Referrer for external links with target=“_blank”? 向所有外部链接添加 target="blank" 的正则表达式 - regular expression to add a target="blank" to all external links 如何使用外部浏览器在WebView中打开目标_blank链接 - how to open target _blank links in WebView with external browser WordPress主题在链接上阻止target =“_ blank”。 如何为某些外部链接重新激活它? - Wordpress theme blocks target=“_blank” on links. How do I reactivate it for some external links? 如何在Ruby on Rails中自动将_blank添加到锚点链接 - How to automatically add _blank to anchor links in Ruby on Rails 如何自动将 rel="noopener" 添加到 target="_blank" 链接? - How to automatically add rel="noopener" to a target="_blank" link? 有没有办法只为重定向的链接制作“target=&#39;_blank&#39;”? - Is there a way to make "target='_blank'" only for the redirected links? 有条件地将target =“_ blank”添加到与Angular JS的链接中 - Conditionally add target=“_blank” to links with Angular JS 如果链接有 http 或 https,则将目标空白添加到链接 - Add target blank to links if it has http or https
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM