일부 태그 설명에 다음과 같은 링크를 추가하고 싶습니다:
<a href="https://store.sgiant.me" target="_blank">여기를 클릭하세요</a> 공식 Sir Giant 스토어를 방문하세요.
처음 저장할 때는 정상 작동하며 새 창에서 열립니다.
하지만 페이지를 새로고침하면 더 이상 작동하지 않고, 코드를 확인해 보면 다음과 같이 변해 있습니다:
<a href="https://store.sgiant.me">여기를 클릭하세요</a> 공식 Sir Giant 스토어를 방문하세요.
외부 링크를 새 탭에서 열라는 옵션을 이미 '예’로 설정해 두었지만, HTML 코드를 직접 추가하는 이 특정 경우에는 해당 옵션이 적용되지 않는 것 같습니다.
ChatGPT는 JS 탭에 다음 내용을 포함하는 컴포넌트를 생성하는 것을 제안했습니다:
import { apiInitializer } from "discourse/lib/api";
export default apiInitializer((api) => {
function processTagLinks() {
document.querySelectorAll('.tag-title-contents a[href^="http"]').forEach(link => {
if (!link.href.includes(window.location.hostname) && !link.hasAttribute('data-processed')) {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener noreferrer');
link.setAttribute('data-processed', 'true');
}
});
}
// 즉시 처리
processTagLinks();
// DOM 변경 사항 감시
const observer = new MutationObserver(() => {
processTagLinks();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
// 페이지 변경 시에도 실행
api.onPageChange(() => {
setTimeout(processTagLinks, 100);
});
});
하지만 저는 개발자가 아니기 때문에 이것이 좋은 해결책인지 아닌지 알 수 없습니다.
