如何让外部链接新标签打开但排除tel和mailto链接?
Fix: Stop tel/mailto Links from Opening in New Tabs (and Fix iPhone 6 Mail Error)
Hey there, let's get that script sorted out! The issue with your current code is that it doesn't distinguish between external web links and tel:/mailto: links — so it's forcing those phone/email links to open in a new tab, which causes that annoying blocked message on older iPhones like the 6.
Here's the adjusted script that fixes this:
jQuery(document).ready(function($) { $('a').each(function() { var internalLinkRegex = new RegExp('/' + window.location.host + '/'); // Only target links that are NOT internal AND NOT tel/mailto if (!internalLinkRegex.test(this.href) && !this.href.startsWith('tel:') && !this.href.startsWith('mailto:')) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } }); });
Key Changes Explained:
- Added two extra checks:
!this.href.startsWith('tel:')and!this.href.startsWith('mailto:')to exclude those protocol links from the new-tab behavior. - Now, only external web URLs (like
https://example.com) will open in a new tab, whiletel:links will trigger the phone app andmailto:links will open the default email client as expected.
Alternative Approach (More Future-Proof):
If you want to cover other non-web protocols (like sms: or whatsapp:) without adding more checks, you can instead only target links using http/https:
jQuery(document).ready(function($) { $('a').each(function() { var internalLinkRegex = new RegExp('/' + window.location.host + '/'); // Only target http/https links that are external if (this.href.startsWith('http') && !internalLinkRegex.test(this.href)) { $(this).click(function(event) { event.preventDefault(); event.stopPropagation(); window.open(this.href, '_blank'); }); } }); });
This way, any link that doesn't use the web protocol is automatically ignored, so you won't have to update the script if you add other protocol links later.
内容的提问来源于stack exchange,提问作者April Marshall
相关产品推荐
相关产品推荐

