I use contentscript to query a webpage via the DOM to grab some text. I then send this text to popup.js
as the text will be used as title for a newly created tab group.
I find my current approach to not be ideal as sometimes an undefined
value is returned.
My goal is for the content script to fire whenever there’s a new active tab (new url) and page refresh. I want to grab the text immediately and store it for my popup to use
Contentscript.js
– Here I need to query the DOM for some text which is important for the extension. I then need to send the text to the background asap
let workspaceName;
const target = '.db';
const observer = new MutationObserver((mutationsList, observer) => {
if (document.querySelector(target)) {
let name = getWorkspaceDetails();
observer.disconnect();
// heres where I send the message
chrome.runtime.sendMessage(null, name);
}
});
observer.observe(document.body, { childList: true, subtree: true });
function getWorkspaceDetails() {
workspaceName = document.querySelector(target);
console.log(workspaceName.textContent);
return workspaceName.textContent;
}
// Initial check in case the element is already present
if (document.querySelector(target)) {
getWorkspaceDetails();
observer.disconnect();
}
background.js
and popUp.js
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
workspaceName = msg;
console.log(`Workpspace: ${msg}`);
});
This only runs on page page refresh and when extension is open. Perhaps this is nature of background script.
3