Change Search AI (Chatbar) links to open in current window

User the default callback to alter the HTML

The AI Search results will often contain links to other pages and clicking on them will cause the page to open in a new tab. If you would rather that the links open in the current page you can add a simple callback which is executed immediately after the AI response is displayed on the page. This callback can find the last response and alter the anchor tag to make the link open in the current window. The code below is a full example.

async function AiLinkProcessorCallback(chatMessage, answer) {
  // Find the last element with _bl_ai-response class
  const aiResponseElements = document.querySelectorAll("._bl_ai-response");
  const aiResponseElement = aiResponseElements[aiResponseElements.length - 1];

  if (aiResponseElement) {
    // Find all tags within the response and replace target="_blank" with target="_self"
    const links = aiResponseElement.querySelectorAll('a[target="_blank"]');
    links.forEach((link) => {
      link.setAttribute("target", "_self");
    });
  }
}

const _ai_config = await _bl_ai_search.init(null, _cb_ai_element, {
  callback: AiLinkProcessorCallback,
});