0

I have a chrome extension for fillling forms on certain websites. This all works well, however sporadically the content script for filling the form doesn't get injected anymore, then I have to reinstall the extension to remediate the problem. This is the code I use for injecting the content script:

chrome.tabs.create({ url: url, active: true }, function (tab) {  //create tab
    chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (info.status === 'complete' && tabId === tab.id) {
            chrome.tabs.onUpdated.removeListener(listener);               
                chrome.tabs.executeScript(tab.id, { file: 'library.js', allFrames: true, runAt: "document_end" }, function () {                        
                    chrome.tabs.executeScript(tab.id, { file: 'fillForm.js', allFrames: true, runAt: "document_end" }, function () {
                        //inject content script
                        chrome.tabs.sendMessage(tab.id, { formData });  //send message to content script
                    });
            });
        }
    });
});

I suppose it's some kind of a timing issue or something that changed in the Chrome api? Because the problem only occured recently.

aynber
  • 22,380
  • 8
  • 50
  • 63
Isostorm
  • 1
  • 2
  • 1
    Remove both chrome.tabs.onUpdated lines and just call executeScript right inside the callback of create(). – wOxxOm Jun 08 '22 at 07:31

1 Answers1

0

You're right. It's a bug with executeScript timing. here is how I solved it; more a hack than a solution, but it works, injecting scripts to generated tabs consistently:

function _func(res){
    setTimeout( () => {
    // Do things with the page.
    }, 3000);
}
chrome.tabs.create({url: 'https://www.example.com'}).then((tab) => {
    setTimeout(() => {
        chrome.scripting.executeScript({
            target: {tabId: tab.id},
            func: _func //,
            // I used args in my case, you dont have to. args: [msg.content]
        })
    }, 3000)
});
A. Abramov
  • 1,823
  • 17
  • 45