diff --git a/preview-src/index.adoc b/preview-src/index.adoc index a3b76d1..3f1d5a8 100644 --- a/preview-src/index.adoc +++ b/preview-src/index.adoc @@ -56,6 +56,9 @@ And this also should not: [.no-query-replace]`%USER%` You should see USER replacement here: %USER% but not here: [.no-query-replace]#%USER%# +=== Xrefs + +xref:index.adoc#link-testing[This,role="page"] is an xref that needs the query string preserved. == Cu solet diff --git a/src/js/07-userparams-behaviour.js b/src/js/07-userparams-behaviour.js index 065f098..9a7058d 100644 --- a/src/js/07-userparams-behaviour.js +++ b/src/js/07-userparams-behaviour.js @@ -3,12 +3,17 @@ document.addEventListener('DOMContentLoaded', function () { // If there is a query string, we need to fix up the page to make sure the query string is properly preserved var desiredQueryString = new URLSearchParams(window.location.search) if (desiredQueryString.toString()) { - preserveQueryString(desiredQueryString) + // If there are query parameters (searchparams) in the current window location // then iterate over all them replacing text and link-hrefs that contain them for (var k of desiredQueryString.keys()) { replaceParamsInNodes(document.body, k, desiredQueryString.get(k)) } + + // NOTE: Once all links have been query string replaced, then attempt to preserve the query string + // for all references + preserveQueryString(desiredQueryString) + } function preserveQueryString (desiredQueryString) { @@ -23,17 +28,27 @@ document.addEventListener('DOMContentLoaded', function () { if (paramLinks) { paramLinks.forEach(appendQueryStringToHref) } + + // Handle xrefs, which are anchor elements generated by antora with the page attribute + var xrefLinks = document.querySelectorAll('a.page') + if (xrefLinks) { + xrefLinks.forEach(appendQueryStringToHref) + } } function appendQueryStringToHref (el) { // NOTE: desiredQueryString captured from above if (desiredQueryString.toString()) { - var hrefURL = new URL(el.href) - for (var k of desiredQueryString.keys()) { - hrefURL.searchParams.set(k, desiredQueryString.get(k)) - } + try { + var hrefURL = new URL(el.href) + for (var k of desiredQueryString.keys()) { + hrefURL.searchParams.set(k, desiredQueryString.get(k)) + } - el.href = hrefURL.toString() + el.href = hrefURL.toString() + } catch (err) { + console.error('Unable to append query string to element [' + el.innerHTML + ']: ' + err) + } } }