Skip to content

Instantly share code, notes, and snippets.

@gerwld
Created February 1, 2025 11:56
Show Gist options
  • Save gerwld/d4b3b2200eeaf33725c852964e4a161c to your computer and use it in GitHub Desktop.
Save gerwld/d4b3b2200eeaf33725c852964e4a161c to your computer and use it in GitHub Desktop.
Inject script for DOM that often rerenders on start
(() => {
function injectButton(parent) {
if (parent.querySelector(".pf_lb2")) return; // Prevent duplicates
const wrapper = document.createElement("div");
wrapper.innerHTML = `<!-- CONTENT -->`;
parent.prepend(wrapper);
}
function waitForReactElement(attempts = 0, maxAttempts = 100) {
const selector = ".parent";
const check = () => {
const parent = document.querySelector(selector);
if (parent) {
injectButton(parent);
observeChanges(parent);
} else if (attempts < maxAttempts) {
setTimeout(() => waitForReactElement(attempts + 1, maxAttempts), 200);
} else {
console.warn(`Element '${selector}' not found after ${maxAttempts} attempts.`);
}
};
check();
}
function observeChanges(target) {
const observer = new MutationObserver(() => injectButton(target));
observer.observe(target, { childList: true, subtree: true });
}
waitForReactElement();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment