How to create links in Memberstack comments without modifying core functionality? Answered

Post author
Marius

Is there any way to make this a link? (memberstack comments)

Comments

2 comments

  • Comment author
    Duncan from Memberstack

    Yes, via custom code. I thought I created a script for this, but I must have been unable to finish it.
    You'll need the code to look for text that starts with https, wrap it in a tags.

    0
  • Comment author
    A J
    Hey Marius, I had come up with a script for this use-case.
     
    So you can paste this code in your Before </body> of custom code section in the page you are hosting the comments:
     
    <script> 
    const commentsContainer = document.querySelector(".comment-post-container");

    function wrapUrl(text) {
    const urlRegex = /\b(https?:\/\/)?www\.[^\s]+\.[^\s]+|
    (https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, (url) => {
    if (!url.startsWith("http")) {
    url = "https://" + url;
    }
    return `<a href="${url}" target="_blank">${url}</a>`;
    });
    }

    const commentObserver = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
    if (mutation.added nodes.length) {
    const newComments = mutation.addedNodes;
    newComments.forEach((comment) => {
    const commentContent = comment.querySelector(".comment-hover");
    if (commentContent &&
    commentContent.querySelector(".comment-text")) {
    const commentText =
    commentContent.querySelector(".comment-text").textContent;
    const updatedText = wrapUrl(commentText);
    commentContent.querySelector(".comment-text").innerHTML = updatedText;
    }
    });
    }
    });
    });
    commentObserver.observe(commentsContainer , { childList: true });
    </script>
     
    I have tested this on a dummy site and below is how the result looks like. It's also instantaneous, i.e. new comments will also be hyperlinked, not just the already existing ones while the user visits the page.
     
    I am not sure which comment component you are using exactly, so you might need to update the class names in the code based on your site. Hope this helps.
    0

Please sign in to leave a comment.