Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch Blacklight.modal.receiveAjax to execute recaptcha #3762

Merged
merged 1 commit into from
Jan 22, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions app/javascript/application.js
Original file line number Diff line number Diff line change
@@ -52,6 +52,39 @@ import "./tooltip";
import "./truncate";
import "./update-hidden-inputs-by-checkbox";


// TODO: Remove this whole method when we upgrade to Blacklight 8, provided that
// https://github.com/projectblacklight/blacklight/pull/3133 is merged
//
// Add the passed in contents to the modal and display it.
// We have specific handling so that scripts returned from the ajax call are executed.
// This enables adding a script like recaptcha to prevent bots from sending emails.
Blacklight.modal.receiveAjax = function (contents) {
const domparser = new DOMParser();
const dom = domparser.parseFromString(contents, "text/html")
// If there is a containerSelector on the document, use its children.
let elements = dom.querySelectorAll(`${Blacklight.modal.containerSelector} > *`)
const frag = document.createDocumentFragment()
if (elements.length == 0) {
// If the containerSelector wasn't found, use the whole document
elements = dom.body.childNodes
}
elements.forEach((el) => frag.appendChild(el))

// DOMParser doesn't allow scripts to be executed. This fixes that.
frag.querySelectorAll('script').forEach((script) => {
const fixedScript = document.createElement('script')
fixedScript.src = script.src
fixedScript.async = false
script.parentNode.replaceChild(fixedScript, script)
})

document.querySelector(`${Blacklight.modal.modalSelector} .modal-content`).replaceChildren(frag)

Blacklight.modal.show();
};


// Prevent the back-button from trying to add a second instance of recaptcha
// See https://github.com/ambethia/recaptcha/issues/217#issuecomment-615221808
document.addEventListener("turbo:before-cache", function () {