Last active
March 19, 2023 00:43
-
-
Save Neboer/e307e5e97b93992e88f18781d0514360 to your computer and use it in GitHub Desktop.
This code piece can be used in Tempermonkey scripts. Execute it on page init and it will wait for dom until target element shows up. Then you can get the elements you requested and work with it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// need piority: document-start | |
function waitForElm(selector_list) { | |
let result_list = new Array(selector_list.length).fill(null) | |
// request all elements in selector, if all elements are set, then return true. | |
function collect_selection() { | |
selector_list.forEach((value, index) => { | |
if (!result_list[index]) { | |
let search_result = document.querySelector(value); | |
if (search_result) result_list[index] = search_result | |
} | |
}) | |
} | |
function check_list_complete() { | |
return !result_list.some(item => item === null); | |
} | |
return new Promise(resolve => { | |
collect_selection() | |
if (!check_list_complete()) { | |
const observer = new MutationObserver(() => { | |
collect_selection() | |
if (check_list_complete()) { | |
resolve(result_list); | |
observer.disconnect(); | |
} | |
}); | |
observer.observe(document.body, { | |
childList: true, | |
subtree: true | |
}); | |
} else { | |
resolve(result_list) | |
} | |
}); | |
} | |
// example for bilibili.com | |
waitForElm(['.bpx-player-video-wrap video', '.bpx-player-dm-root', '.bpx-player-video-inputbar']).then(elements => { | |
let [bilibili_video_element, toolbox_element, toolbox_danmu_input_box_element] = elements; | |
console.log(bilibili_video_element, toolbox_element, toolbox_danmu_input_box_element); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment