0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-23 02:57:52 +00:00

fix mutation observer integration

This commit is contained in:
Víctor Losada Hernández
2024-10-17 23:38:11 +02:00
parent 9a4473526a
commit d872a496a7

View File

@@ -78,39 +78,44 @@ const BrewRenderer = (props)=>{
}
useEffect(() => {
const iframeDoc = document.getElementById('BrewRenderer');
const iframe = document.getElementById('BrewRenderer');
const hash = window.location.hash;
console.log('Hash: ', hash || 'There is no hash');
console.log(iframeDoc || 'no iframe yet');
if(hash && iframeDoc) {
const anchor = iframeDoc.querySelector(hash);
const scrollToHash = () => {
const iframeDoc = iframe?.contentDocument || iframe?.contentWindow?.document;
let anchor = iframeDoc.querySelector(hash);
if (anchor) {
anchor.scrollIntoView();
anchor.scrollIntoView({ behavior: 'smooth' });
} else {
// Use MutationObserver to wait for the element if it's not immediately available
const observer = new MutationObserver((mutations, obs) => {
const anchorElement = iframeDoc.querySelector(hash);
if(anchorElement) {
anchorElement.scrollIntoView();
obs.disconnect(); // Stop observing once the element is found
anchor = iframeDoc.querySelector(hash);
if (anchor) {
anchor.scrollIntoView({ behavior: 'smooth' });
obs.disconnect();
}
});
observer.observe(iframeDoc, {
if (iframeDoc.body) {
observer.observe(iframeDoc.body, {
childList: true,
subtree: true,
});
}
}
/*
const elementId = window.location.hash.slice(1);
if(elementId && state.isMounted) {
const element = document.getElementById(elementId);
element.scrollIntoView({ block: 'start' });
};
if (hash) {
iframe.addEventListener('load', scrollToHash);
if (iframe.contentDocument?.readyState === 'complete') {
scrollToHash();
}
*/
}
return ()=>{
iframe.removeEventListener('load', scrollToHash);
window.removeEventListener('resize', updateSize);
};
}, []);