I am simply querying a web page for specific text to save to local storage and use within Chrome extension pop-up.
contentscript.js
– Code I inject to webpage
function findworkspaceName() {
let target = '#name > .company';
const observer = new MutationObserver((mutationsList, observer) => {
if (document.querySelector(target)) {
let name = getDetails();
chrome.storage.local.set({ name });
observer.disconnect();
}
});
observer.observe(document.body, { childList: true, subtree: true });
function getDetails() {
let workspaceName = document.querySelector(target);
console.log(workspaceName);
console.log(workspaceName.textContent);
return workspaceName.textContent;
}
// Initial check in case the element is already present
if (document.querySelector(target)) {
getWorkspaceDetails();
observer.disconnect();
}
}
findworkspaceName();
Now just focusing on getDetails
function. Console logging workspaceName
seems to return the div in the console consistently. However, console logging workspaceName.textContent
does not always return the textcontent from the div. Sometimes it’s empty and sometimes it correctly shows the text:
function getDetails() {
let workspaceName = document.querySelector(target);
console.log(workspaceName); // works 100%
console.log(workspaceName.textContent); // Is inconsistent
return workspaceName.textContent;
}
Why could this be occuring?