jQuery / javascript로 링크가 외부에 있는지 테스트?
링크가 외부인지 내부인지 테스트하려면 어떻게 해야 합니까?참고:
- 로컬 도메인을 하드코딩할 수 없습니다.
- "http"를 테스트할 수 없습니다.저는 http absolute link로 제 사이트에 쉽게 연결할 수 있습니다.
- CSS가 아닌 jQuery / javascript를 사용하고 싶습니다.
답은 어딘가 위치에 있을 것으로 생각합니다.href, 하지만 그 해결책은 나를 피합니다.
감사합니다!
저는 이 게시물이 오래된 것을 알고 있지만 여전히 결과 상단에 표시되어 있어서 다른 접근 방법을 제안하고 싶었습니다. 정규성 요?window.location.host
합니다를 합니다.host
재산?
function link_is_external(link_element) {
return (link_element.host !== window.location.host);
}
jQuery 사용:
$('a').each(function() {
if (link_is_external(this)) {
// External
}
});
그리고 일반 자바스크립트로:
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
if (link_is_external(links[i])) {
// External
}
}
var comp = new RegExp(location.host);
$('a').each(function(){
if(comp.test($(this).attr('href'))){
// a link that contains the current host
$(this).addClass('local');
}
else{
// a link that does not contain the current host
$(this).addClass('external');
}
});
참고: 이것은 단지 빠르고 더러운 예일 뿐입니다.모든 href="# anchor" 링크도 외부 링크와 일치합니다.추가 RegExp 점검을 통해 개선될 수도 있습니다.
업데이트 2016-11-17
이 질문은 여전히 많은 사람들의 관심을 끌었고, 많은 사람들로부터 이 수용된 해결책이 여러 번 실패할 것이라는 말을 들었습니다.제가 말했듯이, 이것은 이 문제를 해결하는 주요한 방법을 보여주는 매우 빠르고 더러운 대답이었습니다.더 입니다.<a>
(앵커)소 이지적한 @처럼 @Daved처럼,입니다를입니다.hostname
window.location.hostname
. .hostname
들,하지 않기 입니다.port
다에 .host
80과 다를 경우에는 재산을 계산할 수 있습니다.
자, 시작합니다.
$( 'a' ).each(function() {
if( location.hostname === this.hostname || !this.hostname.length ) {
$(this).addClass('local');
} else {
$(this).addClass('external');
}
});
최신 기술:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
그리고 노제이쿼리 방식.
var nodes = document.getElementsByTagName("a"), i = nodes.length;
var regExp = new RegExp("//" + location.host + "($|/)");
while(i--){
var href = nodes[i].href;
var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true;
alert(href + " is " + (isLocal ? "local" : "not local"));
}
가 href로 http
((http://, https://)다로 됩니다.
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')');
용도:
external.test('some url'); // => true or false
외부 링크만을 위한 jQuery 셀렉터는 다음과 같습니다.
$('a[href^="(http:|https:)?//"])')
내부 링크(같은 페이지 내에 해시 링크를 포함하지 않음)에 대한 jQuery 선택기는 조금 더 복잡해야 합니다.
$('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])')
수 .:not()
조건과 필요에 따라 추가 쉼표로 구분합니다.
http://jsfiddle.net/mblase75/Pavg2/
를 도 있습니다.href
항상 대 URL인 속성:
$('a').filter( function(i,el) {
return el.href.indexOf(location.protocol+'//'+location.hostname)===0;
})
http://jsfiddle.net/mblase75/7z6EV/
하나를 잊어버렸군요, 상대적인 경로를 사용한다면요.
예: /test
hostname = new RegExp(location.host);
// Act on each link
$('a').each(function(){
// Store current link's url
var url = $(this).attr("href");
// Test if current host (domain) is in it
if(hostname.test(url)){
// If it's local...
$(this).addClass('local');
}
else if(url.slice(0, 1) == "/"){
$(this).addClass('local');
}
else if(url.slice(0, 1) == "#"){
// It's an anchor link
$(this).addClass('anchor');
}
else {
// a link that does not contain the current host
$(this).addClass('external');
}
});
"로컬 다운로드" 또는 "외부 다운로드" 클래스를 사용할 수 있는 파일 다운로드 .zip(로컬 외부) 문제도 있습니다.하지만 아직 해결책을 찾지 못했습니다.
const isExternalLink = (url) => {
const tmp = document.createElement('a');
tmp.href = url;
return tmp.host !== window.location.host;
};
// output: true
console.log(isExternalLink('https://foobar.com'));
console.log(isExternalLink('//foobar.com'));
// output: false
console.log(isExternalLink('https://www.stackoverflow.com'));
console.log(isExternalLink('//www.stackoverflow.com'));
console.log(isExternalLink('/foobar'));
console.log(isExternalLink('#foobar'));
이 접근 방식을 사용함으로써 얻을 수 있는 이점은 다음과 같습니다.
- 자동으로 됩니다.
hostname
및 - 작동합니다.
protocol-relative
URL
이를 입증하기 위해 다음 예를 살펴봅니다.
const lnk = document.createElement('a');
lnk.href = '/foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '#foobar';
console.log(lnk.host); // output: 'www.stackoverflow.com'
const lnk = document.createElement('a');
lnk.href = '//www.stackoverflow.com';
console.log(lnk.host); // output: 'www.stackoverflow.com'
위드제이쿼리
jQuery('a').each(function() {
if (this.host !== window.location.host) {
console.log(jQuery(this).attr('href'));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
is-url-external 모듈을 사용할 수 있습니다.
var isExternal = require('is-url-external');
isExternal('http://stackoverflow.com/questions/2910946'); // true | false
/**
* All DOM url
* [links description]
* @type {[type]}
*/
var links = document.querySelectorAll('a');
/**
* Home Page Url
* [HomeUrl description]
* @type {[type]}
*/
var HomeUrl = 'https://stackoverflow.com/'; // Current Page url by-> window.location.href
links.forEach(function(link) {
link.addEventListener('click', function(e) {
e.preventDefault();
// Make lowercase of urls
var url = link.href.toLowerCase();
var isExternalLink = !url.includes(HomeUrl);
// Check if external or internal
if (isExternalLink) {
if (confirm('it\'s an external link. Are you sure to go?')) {
window.location = link.href;
}
} else {
window.location = link.href;
}
})
})
<a href="https://stackoverflow.com/users/3705299/king-rayhan">Internal Link</a>
<a href="https://wordpress.stackexchange.com/">External Link</a>
이것은 IE를 제외한 모든 브라우저의 어떤 종류의 링크에서도 작동해야 합니다.
// check if link points outside of app - not working in IE
try {
const href = $linkElement.attr('href'),
link = new URL(href, window.location);
if (window.location.host === link.host) {
// same app
} else {
// points outside
}
} catch (e) { // in case IE happens}
네, 현재 도메인 이름은 location.href로 검색하실 수 있을 것 같습니다.링크 요소를 만들고 src를 /로 설정한 다음 표준 URL을 검색하는 것도 가능합니다(도메인 이름이 아니라 사용할 경우 기본 URL을 검색합니다).
다음 게시물도 참조하십시오.링크의 href 속성에서 전체 URI 가져오기
관심 있는 분들을 위해 if block의 ternary version을 요소가 어떤 클래스가 있는지, 어떤 클래스가 붙었는지 체크해 보았습니다.
$(document).ready(function () {
$("a").click(function (e) {
var hostname = new RegExp(location.host);
var url = $(this).attr("href");
hostname.test(url) ?
$(this).addClass('local') :
url.slice(0, 1) == "/" && url.slice(-1) == "/" ?
$(this).addClass('localpage') :
url.slice(0, 1) == "#" ?
$(this).addClass('anchor') :
$(this).addClass('external');
var classes = $(this).attr("class");
console.log("Link classes: " + classes);
$(this).hasClass("external") ? googleAnalytics(url) :
$(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local");
});
});
Google Analytics 비트는 무시할 수 있지만 링크 유형을 알고 있으므로 URL을 사용하여 작업을 수행할 수 있습니다.3진 블록 안에 코드만 추가하면 됩니다.링크의 종류가 1개만 확인하고 싶다면 대신 if문으로 ternaries를 대체합니다.
우연히 발견한 문제를 추가하기 위해 편집되었습니다.몇몇은 "/Coures/" 라는 말을 했습니다.href 시작과 끝에 슬래시가 있는지 확인하는 로컬 페이지를 확인했습니다.시작할 때 '/'를 확인하는 것만으로도 충분할 것입니다.
jQuery의 경우 이 함수를 사용합니다.
$.fn.isExternal = function() {
var host = window.location.host;
var link = $('<a>', {
href: this.attr('href')
})[0].hostname;
return (link !== host);
};
:$('a').isExternal();
예: https://codepen.io/allurewebsolutions/pen/ygJPgV
이것은 질문의 "내 도메인을 하드코딩할 수 없음" 전제 조건을 정확히 충족하지는 않지만, 유사한 솔루션을 검색하는 이 게시물을 찾았고, 내 경우 내 URL을 하드코딩할 수 있습니다.제가 걱정한 것은 사용자에게 사이트를 떠나지만 하위 도메인을 포함하여 사이트에 남아 있는 경우에는 그렇지 않다는 것을 알리는 것이었습니다(example: blog.mysite.com . 다른 답변에서는 대부분 실패합니다.여기 제 해결책이 있습니다. 위에서 투표한 답변에서 약간의 정보를 얻을 수 있습니다.
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( a.hostname.includes("mywebsite.com") ? 'local' : 'external' );
});
$("a").on("click", function(event) {
if ($(this).hasClass('local')) {
return;
} else if ($(this).hasClass('external')) {
if (!confirm("You are about leave the <My Website> website.")) {
event.preventDefault();
}
}
});
이것은 나에게 효과가 있습니다.
function strip_scheme( url ) {
return url.replace(/^(?:(?:f|ht)tp(?:s)?\:)?\/\/(www\.)?/g, '');
}
function is_link_external( elem ) {
let domain = strip_scheme( elem.attr('href') );
let host = strip_scheme( window.location.host );
return ! domain.indexOf(host) == 0;
}
2023년을 기점으로 이렇게 하는 것이 저를 위한 일이 되었습니다.
export function isInternalLink(urlString: string): boolean | {
pathname: string;
} {
const url = new URL(urlString);
if (url.origin !== window.location.origin) {
return false;
}
return {
pathname: url.pathname,
};
}
언급URL : https://stackoverflow.com/questions/2910946/test-if-links-are-external-with-jquery-javascript
'bestsource' 카테고리의 다른 글
WooCommerce API : 온라인상의 메타데이터로 주문생성 (0) | 2023.09.26 |
---|---|
각 ID에 대해 최신 날짜가 여러 번 반복되는 SQL에서 행 선택 (0) | 2023.09.26 |
핵심 파일을 재정의하지 않고 BACS 계정 필드에 사용자 정의 필드 추가 (0) | 2023.09.26 |
빈 셀을 제거하는 간단한 방법 동적 드롭다운 목록 Excel (0) | 2023.09.26 |
Windows 업데이트의 적용 가능성 규칙을 프로그래밍 방식으로 확인하는 방법은 무엇입니까? (0) | 2023.09.26 |