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?