Userscript to wait for page to load before executing code techniques?

前端 未结 7 2004
迷失自我
迷失自我 2020-11-27 10:24

I\'m writing a Greasemonkey user script, and want the specific code to execute when the page completely finishes loading since it returns a div count that I want to be displ

7条回答
  •  佛祖请我去吃肉
    2020-11-27 11:13

    If you want to manipulate nodes like getting value of nodes or changing style, you can wait for these nodes using this function

    const waitFor = (...selectors) => new Promise(resolve => {
        const delay = 500
        const f = () => {
            const elements = selectors.map(selector => document.querySelector(selector))
            if (elements.every(element => element != null)) {
                resolve(elements)
            } else {
                setTimeout(f, delay)
            }
        }
        f()
    })
    

    then use promise.then

    // scripts don't manipulate nodes
    waitFor('video', 'div.sbg', 'div.bbg').then(([video, loading, videoPanel])=>{
        console.log(video, loading, videoPanel)
        // scripts may manipulate these nodes
    })
    

    or use async&await

    //this semicolon is needed if none at end of previous line
    ;(async () => {
        // scripts don't manipulate nodes
        const [video, loading, videoPanel] = await waitFor('video','div.sbg','div.bbg')
        console.log(video, loading, video)
        // scripts may manipulate these nodes
    })()
    

    Here is an example icourse163_enhance

提交回复
热议问题