Goal
- Query the DOM for
workspaceName
via contentscript - Send
workspaceName
via Sendmessage fromcontentscript.js
topopup.js
- Click button to create tabgroup and Populate
tabgroup
title withworkspaceName
Expected behaviour
For the queried workspaceName
to successfully populate in tabGroup title when tabgroup is created
Current behaviour
On first page load, the sendmessage event does not send (I can observe this in the console) and when I click button to create tabgroup the title is populated with undefined
Set-up
HTML
<button id="createTab">Click me</button>
Contentscript.js
– I have to use MutationObserver as target element loads pretty late
let workspaceName;
const target = '.db-space';
const observer = new MutationObserver((mutationsList, observer) => {
if (document.querySelector(target)) {
let name = getWorkspaceDetails();
observer.disconnect();
chrome.runtime.sendMessage(null, name); // heres where I send the 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();
}
Popup.js
const createBtn = document.queryselector('#createTab');
createBtn.addEventListener('click', createTabs)
let workspaceName;
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
workspaceName = msg;
console.log(`Workpspace: ${msg}`);
});
function createTabs() {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, async (tabs) => {
await chrome.tabs
.create({ url: `https://example1.com`, active: false })
.then((tab) => tabsToGroup.push(tab.id));
await chrome.tabs
.create({ url: `https://example2.com`, active: false })
.then((tab) => tabsToGroup.push(tab.id));
await chrome.tabGroups.update(groupId, {
collapsed: true,
title: `${workspaceName}`,
color: 'red'
});
});
}
Below is how the tab group looks on the first run. After a few pages refreshes it begins to populate