Search code examples
javascripthtmldomgoogle-chrome-extension

Content script – Function returning "Null" value after accessing DOM when page load has completed


Goal - I am building a Chrome extension. I need to access DOM elements from a specific web page once the page and all DOM elements have loaded.

Index.html – Page I am accessing

 <div class="db">some text</div>

Current behaviour – My function returns

Null

Expected behaviour – I expected to see the below within my console once the page completed loading

<div class="db">some text</div>

Contentscript.js – Below is script that runs once page has loaded

window.addEventListener('load', getWorkspaceDetails);

function getWorkspaceDetails() {
    let workspaceName = document.querySelector('.db');
    console.log(workspaceName);
};

Below is the only situation where the console logs expected DOM element

setTimeout(() => {
    let workspaceName = document.querySelector('.db');
    console.log(workspaceName);
  };
}, 5000);

It feels the query did not respect the page load and thus the query failed. I prefer not to use setTimeout. How can I ensure window.addEventListener() works as expected?


Solution

  • This is because the "target" element loads after the window is fully loaded.

    For this, you can use a MutationObserver to monitor changes in the DOM and execute the function when the "target" element is detected.

    This way, you can avoid setTimeout and make sure that the function runs as soon as the element is available:

    const target = '.db';
    
    const observer = new MutationObserver((mutationsList, observer) => {
        if (document.querySelector(target)) {
            getWorkspaceDetails();
            observer.disconnect();
        }
    });
    
    observer.observe(document.body, { childList: true, subtree: true });
    
    function getWorkspaceDetails() {
        let workspaceName = document.querySelector(target);
        console.log(workspaceName);
    }
    
    // Initial check in case the element is already present
    if (document.querySelector(target)) {
        getWorkspaceDetails();
        observer.disconnect();
    }