It would be great to be able to share clickable urls/links in the comments widget
1 Like
Hi there, @Jessica_HW and welcome to the Community ![]()
I totally agree that it would be great to make the links clickable by default. We’ll try to consider this feature in the future, especially if more users upvote it.
As for now, we’ve made the links clickable in your widget using a custom code in the Custom JS field on the Settings tab of your widget’s settings.
Please check it out and let me know if it worked for you ![]()
Friends, if you’d also want to make the links clickable, please add the code below to the Custom JS field on the Settings tab of your widget’s settings:
const WIDGET_ID = 'YOUR_WIDGET_ID';
const waitForElement = (selector, root = document) =>
new Promise((res) => {
const element = root.querySelector(selector);
if (element) return res(element);
const observer = new MutationObserver(() => {
const el = root.querySelector(selector);
if (el) {
res(el);
observer.disconnect();
}
});
observer.observe(root, { childList: true, subtree: true });
});
const urlRegex = /(https?:\/\/[^\s]+)/g;
function linkifyElement(el) {
if (el.dataset.linkified === "true") return;
const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
const nodes = [];
while (walker.nextNode()) {
if (!urlRegex.test(walker.currentNode.textContent)) continue;
nodes.push(walker.currentNode);
}
nodes.forEach(node => {
const parent = node.parentNode;
const parts = node.textContent.split(urlRegex);
const frag = document.createDocumentFragment();
parts.forEach(part => {
if (urlRegex.test(part)) {
const a = document.createElement("a");
a.href = part;
a.textContent = part;
a.target = "_blank";
a.rel = "noopener noreferrer";
frag.appendChild(a);
} else {
frag.appendChild(document.createTextNode(part));
}
});
parent.replaceChild(frag, node);
});
el.dataset.linkified = "true";
}
function processAll() {
document.querySelectorAll('.es-text-shortener:not([data-linkified])')
.forEach(linkifyElement);
}
waitForElement(`.elfsight-app-${WIDGET_ID} > div`)
.then(() => {
processAll();
const observer = new MutationObserver(mutations => {
let needsUpdate = false;
for (const m of mutations) {
if (m.addedNodes.length > 0) {
needsUpdate = true;
}
}
if (needsUpdate) processAll();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
Note: Do not forget to replace YOUR_WIDGET_ID in the 1st line of the code with the ID of your widget
1 Like
Thank you Max, it works perfectly! I appreciate this so much
1 Like