程序不再运行,因为我添加了等待页面完全加载的功能

问题描述 投票:0回答:1

我的程序运行一系列操作。在每个操作之间,有一个 sleep(1000) 等待页面完全加载。

chrome.runtime.onMessage.addListener((message, _sender, _sendResponse) => {
    if (message.action === 'triggerAction') {
        console.log('Triggering action');
        chrome.tabs.create({ url: urlToVisit }, (tab) => {
            console.log('TAB ID: ', tab.id);
            (async function () {

                for (let action of actions) {

                    console.log('ABOUT TO EXECUTE SCRIPT', action.type);
                    chrome.scripting.executeScript(
                        {
                            target: { tabId: tab.id },
                            func: performAction,
                            args: [action]
                        }, () => {
                            console.log('Content script injected');
                        });
                    await sleep(1000); // 1 second pause

                }
                console.log('SCRIPT EXECUTED');
            })();
        })
    }
});

我想用等待页面内容完全加载的侦听器替换此睡眠。但这似乎是无限期的等待。因此,这一系列操作不再执行。 这是添加了侦听器的当前版本:

chrome.runtime.onMessage.addListener((message, _sender, _sendResponse) => {
    if (message.action === 'triggerAction') {
        console.log('Triggering action');
        chrome.tabs.create({ url: urlToVisit }, (tab) => {
            console.log('TAB ID: ', tab.id);
            (async function () {

                for (let action of actions) {

                    await new Promise(resolve => {
                        chrome.scripting.executeScript(
                            {
                                target: { tabId: tab.id },
                                func: () => {
                                    window.addEventListener('DOMContentLoaded', resolve);
                                }
                            });
                    });


                    console.log('ABOUT TO EXECUTE SCRIPT', action.type);
                    chrome.scripting.executeScript(
                        {
                            target: { tabId: tab.id },
                            func: performAction,
                            args: [action]
                        }, () => {
                            console.log('Content script injected');
                        });

                }
                console.log('SCRIPT EXECUTED');
            })();
        })
    }
});
javascript google-chrome-extension addeventlistener
1个回答
0
投票

是否有可能在执行脚本之前触发

DOMContentLoaded

您可以尝试在致电

if (document.readyState !== loading) resolve();
 之前添加 
window.addEventListener

© www.soinside.com 2019 - 2024. All rights reserved.