Last active
February 6, 2025 01:21
-
-
Save gerwld/b31f8ee74f428e4b4bfc20b1f69936c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This part injects element before DOMContentLoaded event, | |
* and reaplies it each time React / Other framework rerenders the parent component. | |
* | |
* @returns void | |
*/ | |
;(() => { | |
let observer; | |
function injectButton() { | |
console.log('injectButton'); | |
const parent = document.querySelector('.parent-class'); | |
if (!parent) return; | |
// If the button already exists, do nothing | |
if (parent.querySelector('#lbtn')) return; | |
//disconnect the observer to prevent injection during DOM changes | |
if (observer) observer.disconnect(); | |
const wrapper = document.createElement('section'); | |
wrapper.innerHTML = ` | |
<a id="lbtn"> | |
</a> | |
` | |
//insert the button at a stable position | |
if (parent.children.length > 0) { | |
parent.insertBefore(wrapper, parent.children[1]); | |
} else { | |
parent.appendChild(wrapper); | |
} | |
console.log("injectButton success"); | |
// Reattach the observer after injection | |
setTimeout(startObserving, 2000); | |
} | |
function startObserving() { | |
// Disconnect any existing observer instance | |
if (observer) observer.disconnect(); | |
observer = new MutationObserver(() => { | |
// Only schedule injection if the button is missing | |
const parent = document.querySelector('.xl5mz7h.xhuyl8g'); | |
if (!parent) return; | |
if (!parent.querySelector('#lbtn')) { | |
setTimeout(injectButton, 500); | |
} | |
}); | |
observer.observe(document.body, { childList: true, subtree: true }); | |
} | |
function waitForBody() { | |
if (!document.body) { | |
setTimeout(waitForBody, 100); | |
} else { | |
startObserving(); | |
injectButton(); | |
} | |
} | |
waitForBody(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment