mirror of
https://github.com/ajayyy/SponsorBlock.git
synced 2025-12-08 20:47:11 +03:00
Wait for hover preview using mutation observer
This commit is contained in:
39
src/utils.ts
39
src/utils.ts
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user