내부 링크를 현재 창에서, 외부 링크를 새 탭에서 열리도록 설정하기 [자바스크립트]

Last Updated: 2024년 01월 14일 | , | 6개 댓글

Rank Math 등 SEO 플러그인에서는 SEO(검색엔진최적화)를 위해 모든 외부 링크를 새 탭/새 창에서 열리도록 하는 옵션을 제공합니다.

내부 링크를 현재 창에서, 외부 링크를 새 탭에서 열리도록 설정하기 [자바스크립트]
Rank Math SEO에서는 외부 링크를 새 탭에서 열리도록 하는 옵션을 제공한다.

플러그인을 사용하지 않고 모든 링크를 새 창이나 현재 창에서 열리도록 하기를 원하거나 내부 링크는 현재 탭에서 외부 링크는 새 탭에서 열리도록 하고 싶은 경우 자바스크립트를 사용할 수 있습니다.

내부 링크를 현재 창에서, 외부 링크를 새 탭에서 열리도록 설정하기 [자바스크립트]

워드프레스 블록 에디터(구텐베르크)에서 링크를 설정하려는 경우 텍스트를 선택하고 링크 아이콘을 클릭하여 링크를 설정할 수 있지만, 텍스트를 선택한 다음 Ctrl+K 단축키를 눌러 링크를 설정하면 편리합니다(구텐베르크 단축키 참조).

링크를 새 탭에서 열려면 "새 탭에서 열기"(혹은 "Open in New Tab") 옵션을 체크하면 됩니다.

구텐베르크 새 탭에서 열기

자바스크립트를 사용하여 모든 링크 혹은 내부 링크/외부 링크의 작동을 제어할 수 있습니다.

모든 링크를 현재 탭에서 열리도록 하기

예를 들어, 내부 링크와 외부 링크를 불문하고 모든 링크를 현재 창에서 열리도록 하고 싶은 경우 다음과 같은 자바스크립트를 사용할 수 있습니다.

<script>
// 모든 링크를 현재 탭에서 열기
// Get all anchor tags on the page
var links = document.getElementsByTagName("a");

// Loop through each anchor tag
for(var i=0; i<links.length; i++) {

    // Set the target attribute to '_self' for each anchor tag
    // '_self' is the default behavior and will open links in the current tab
    links[i].target='_self';
}
</script>

위의 코드를 사용하면 포스팅 시 특정 링크가 새 탭에서 열리도록 설정해도 무시되고, 현재 창에서 열립니다.

모든 링크를 새 탭에서 열리도록 하기

모든 링크(내외부 링크 모두)를 새 탭/새 창에서 열리도록 설정하고 싶은 경우에는 다음 스크립트를 사용할 수 있습니다.

<script>
// 모든 링크를 새 탭에서 열기
// Get all anchor tags on the page
var links = document.getElementsByTagName("a");

// Loop through each anchor tag
for(var i=0; i<links.length; i++) {

    // Set the target attribute to '_blank' for each anchor tag
    // '_blank' will open links in a new browsing context (new tab or window)
    links[i].target='_blank';
}
</script>

마찬가지로 상기 자스를 사용하면 특정 링크가 현재 탭/현재 창에서 열리도록 설정해도 무시되고 새 탭에서 오픈됩니다.

내부 링크는 현재 탭에서, 외부 링크는 새 탭에서 열리도록 설정하기

SEO를 위해 내부 링크는 현재 탭에서 열리도록 하고, 외부 링크는 새 탭에서 열리도록 하면 좋습니다. 다음과 같은 자바스크립트를 사용할 수 있습니다.

<script>
// 내부 링크는 현재 탭에서 열리도록 하고 외부 링크는 새 탭에서 열리도록 설정하기
// Get all the anchor tags on the page
var links = document.getElementsByTagName("a");

// Get the hostname of the current page
var thisHref = window.location.hostname;

// Loop through each anchor tag
for(var i=0; i<links.length; i++) {

    // Define the current link in the loop
    var link = links[i];

    // Use the getLocation function to create an anchor object for the href of the current link
    // This allows us to access the properties of the link such as hostname
    var a = getLocation(link.href);

    // If the hostname of the current link is the same as the hostname of the page
    if (a.hostname === thisHref) {

        // Remove the 'target' attribute from the link, which defaults it to open in the same tab
        link.removeAttribute("target");

    } else {

        // If the hostname of the link is different from the hostname of the page
        // Set the 'target' attribute of the link to '_blank' which will open it in a new tab
        link.target='_blank';
    }
}

// Function to create an anchor object from a given href
function getLocation(href) {

    // Create a new anchor tag
    var location = document.createElement("a");

    // Set the href of the created anchor tag
    location.href = href;

    // Return the anchor tag object, this can be used to access the properties of the href such as hostname
    return location;
};
</script>

내부 링크를 현재 탭에서 열리도록 설정하기

상기 스크립트를 분리하여 내부 링크만 현재 탭에서 열리도록 하고 싶거나, 외부 링크만 새 탭에서 열리도록 하는 것도 가능합니다.

내부 링크를 현재 탭/현재 창에서 열리도록 하고 싶은 경우 다음 자스 코드를 사용합니다. 이 스크립트를 적용할 경우 외부 링크에는 영향을 미치지 않습니다.

<script>
// 내부 링크를 현재 탭에서 열기
// Get all the anchor tags on the page
var links = document.getElementsByTagName("a");

// Get the hostname of the current page
var thisHref = window.location.hostname;

// Loop through each anchor tag
for(var i=0; i<links.length; i++) {

    // Store the current link in a variable
    var link = links[i];

    // Use the getLocation function to create an object for the href of the current link
    // This allows us to access the properties of the link such as hostname
    var a = getLocation(link.href);

    // If the hostname of the current link is the same as the hostname of the page (i.e., the link is internal)
    if (a.hostname === thisHref){
    
        // Remove the 'target' attribute from the link
        // This ensures the link opens in the same tab
        link.removeAttribute("target");
    }
}

// Function to create an object from a given href
function getLocation(href) {

    // Create a new anchor tag
    var location = document.createElement("a");

    // Set the href of the created anchor tag
    location.href = href;

    // Return the anchor tag object, this can be used to access the properties of the href such as hostname
    return location;
};
</script>

외부 링크를 새 탭에서 열기

외부 링크만 새 탭에서 열리도록 하고 싶은 경우에는 다음 스크립트를 활용할 수 있습니다.

<script>
// 외부 링크를 새 탭에서 열기
// Get all the anchor tags on the page
var links = document.getElementsByTagName("a");

// Get the hostname of the current page
var thisHref = window.location.hostname;

// Loop through each anchor tag
for(var i=0; i<links.length; i++) {

    // Define the current link in the loop
    var link = links[i];

    // Use the getLocation function to create an anchor object for the href of the current link
    // This allows us to access the properties of the link such as hostname
    var a = getLocation(link.href);

    // If the hostname of the current link is different from the hostname of the page
    if (a.hostname !== thisHref){

        // Set the 'target' attribute of the link to '_blank'
        // '_blank' opens the link in a new tab
        link.target='_blank';
    }
}

// Function to create an anchor object from a given href
function getLocation(href) {

    // Create a new anchor tag
    var location = document.createElement("a");

    // Set the href of the created anchor tag
    location.href = href;

    // Return the anchor tag object, this can be used to access the properties of the href such as hostname
    return location;
};
</script>

자바스크립트 로드하기

워드프레스에서 자바스크립트를 로드하려는 경우 다음 글을 참고하여 로드할 수 있습니다.

위의 방법이 번거로운 경우에는 WPCode와 같은 플러그인을 사용하여 푸터 영역에 자바스크립트 코드를 넣을 수 있습니다.

GeneratePress 테마나 Neve 테마를 사용한다면 훅(HooK)을 사용하여 푸터 영역에 코드를 추가할 수 있습니다.

JS 코드 적용 방법 예시

다음 글에서 모든 내부 링크를 현재 창/탭에서 표시되도록 하여 구글 애드센스 수익을 높이는 방법에 대하여 설명되어 있습니다. 구체적으로 JS 파일을 로드하는 방법이 설명되어 있으므로 참고해보시기 바랍니다.

마치며

이상으로 자바스크립트를 사용하여 링크가 새 탭에서 열리도록 할지, 아니면 현재 탭에서 열리도록 할 지를 제어하는 방법을 살펴보았습니다. 필요한 경우 상황에 맞는 코드를 적용할 수 있을 것입니다.

본문에 소개된 코드는 테스트를 거쳤지만, 충분히 테스트되지는 않았습니다. 원하는 대로 작동하지 않는 코드가 있는 경우 아래 댓글을 통해 알려주시면 수정하도록 하겠습니다.

상기 방법은 워드프레스뿐만 아니라 티스토리, HTML 웹사이트 등에서도 활용할 수 있습니다.

참고


6 개 댓글

Leave a Comment

  1. 잘 작동합니다.
    정말 감사합니다. ^_^/

    논외로 고견을 여쭤도 될까합니다.
    제 사이트는 포스팅내의 링크가 대부분 내부링크인데, 애드센스도 cpm으로
    바뀐지금, 체류시간 증대를 위해 현재창이 아닌 새창으로 모두 열도록 바꾸려고 생각중입니다.

    전면광고 클릭으로 수입을 얻기에는 구글 정책이 바뀌어서 그런 것인데, 체류시간 증가를 위한 적절한 방법일까요? ''a

    응답
    • 이 블로그의 경우 내부 링크는 현재 창으로 표시되도록 했고, 외부 링크는 강제로 설정하지는 않았지만 새 창에서 열리도록 설정된 경우가 많습니다.
      이 블로그에서는 CPM 방식으로 바뀐 후에 애드센스 수익에 변화가 있습니다.
      어떤 식으로 링크를 설정하는 것이 애드센스 수익에 유리할지 고민하고 있습니다.
      다양하게 테스트하여 적당한 설정을 찾는 노력이 필요하지 않을까 생각됩니다.
      최근 애드센스 정책이 바뀌어 새 창에서 열리든, 현재 창에서 열리든 전면 광고가 표시되지만, 새 창에서 열리도록 할 경우 외부 창으로 이동했다가 다시 되돌아와야 광고를 볼 수 있습니다. 외부 링크를 현재 창에서 열리도록 하면 이탈률이 높아져서 SEO적인 측면에서는 좋지 않을 것 같습니다.

      응답
  2. 안녕하세요. 평소 포스팅 잘 보고 있습니다. 감사합니다.

    다름이 아니라, 위에 예시 코드 중 내부/외부 링크를 모두 새창으로 여는 소스를 사용해보니, 포스팅 목차까지도 클릭하면 새창으로 열립니다. -0-;;
    (쉬운 목차 플러그인을 사용중입니다.)

    홈페이지의 카테고리나, 목차를 제외한 순수 포스팅 글에 있는 링크만 내부/외부 모두 새창으로 열수 있는 추가 코드를 알 수 있을까요? ''a

    응답