
<script type="text/javascript">
(function() {

  var origin = "<%- origin %>";
  var search = "<%- search %>";

  function isLocalHref(href) {
    return href.startsWith(origin);
  }

  function ensureLinkOpensInNewWindow(linkEl) {

    var useOpenExternalMessage =
      search.includes("quartoPreviewReqId=") &&
      window.parent.postMessage;

    if (useOpenExternalMessage) {
      linkEl.addEventListener("click", function(event) {
        window.parent.postMessage({
          type: "openExternal",
          url: linkEl.href,
        }, "*");
        event.preventDefault();
        return false;
      });
    }

    var isRStudio = search.includes("capabilities=");
    if (isRStudio) {
      linkEl.target = "_blank";
    }

  }

  function initialize() {
    // only do this if we are in an iframe
    try {
      if (window.self === window.top) {
        return;
      }
    // added during rc phase of v1.2 -- don't allow
    // unexpected exceptions to derail the feature
    } catch {
      return;
    }
   
    var linkEls = document.getElementsByTagName("a");
    for (var linkEl of linkEls) {
      if (linkEl.href && !isLocalHref(linkEl.href)) {
        ensureLinkOpensInNewWindow(linkEl);
      }
    }
  }

  initialize();

})();

</script>
