Wait for hover preview using mutation observer

This commit is contained in:
Ajay
2022-01-19 11:27:19 -05:00
parent bf735f47b0
commit 002f22c040
4 changed files with 42 additions and 9 deletions

View File

@@ -21,6 +21,10 @@ export default class Utils {
"popup.css"
];
/* Used for waitForElement */
waitingMutationObserver:MutationObserver = null;
waitingElements: { selector: string, callback: (element: Element) => void }[] = [];
constructor(backgroundScriptContainer: BackgroundScriptContainer = null) {
this.backgroundScriptContainer = backgroundScriptContainer;
}
@@ -29,6 +33,41 @@ export default class Utils {
return GenericUtils.wait(condition, timeout, check);
}
/* Uses a mutation observer to wait asynchronously */
async waitForElement(selector: string): Promise<Element> {
return await new Promise((resolve) => {
this.waitingElements.push({
selector,
callback: resolve
});
if (!this.waitingMutationObserver) {
this.waitingMutationObserver = new MutationObserver(() => {
const foundSelectors = [];
for (const { selector, callback } of this.waitingElements) {
const element = document.querySelector(selector);
if (element) {
callback(element);
foundSelectors.push(selector);
}
}
this.waitingElements = this.waitingElements.filter((element) => !foundSelectors.includes(element.selector));
if (this.waitingElements.length === 0) {
this.waitingMutationObserver.disconnect();
this.waitingMutationObserver = null;
}
});
this.waitingMutationObserver.observe(document.body, {
childList: true,
subtree: true
});
}
});
}
containsPermission(permissions: chrome.permissions.Permissions): Promise<boolean> {
return new Promise((resolve) => {
chrome.permissions.contains(permissions, resolve)