executeScript in tabs.create

Hello,

Is it normal executeScript doesn’t work in a new tab creation ?
A minimal exemple :

chrome.tabs.create( {“url”: ‘https://mozilla.org’ } , function(tab){
chrome.tabs.executeScript(tab.id,{ code: “window.addEventListener(‘load’, function(){alert(‘plop’) },false);” })
});

Are you 100% sure that ‘load’ hasn’t fired yet?

In first I try without the evenListener, but it didn’t work , so I tried with it and it’s the same :-/

Well then I suggest you do error handling. Ether read runtime.lastError or use the browser.* APIs with Promises.
I ran this:

browser.tabs.create({ url: 'https://mozilla.org', })
.then(tab => browser.tabs.executeScript(tabId, { code: `alert('plop')`, }))
.catch(error => console.error('FAILED', error));

In my add-on, it didn’t work, but the mistake was quite obvious once printed to the console.

1 Like

Your issue is that the following two code snippets are equivalent:

chrome.tabs.create({url: "https://mozilla.org"}, function (tab) {
    chrome.tabs.executeScript(tab.id, {
        code: "window.addEventListener('load', function(){alert('plop') },false);"
    });
 });

and:

chrome.tabs.create({url: "https://mozilla.org"}, function (tab) {
    chrome.tabs.executeScript(tab.id, {
        code: "window.addEventListener('load', function(){alert('plop') },false);",
        runAt: "document_idle"
    });
 });

That is, if you do not specify the runAt property in chrome.tabs.executeScript it defaults to document_idle. document_idle occurs after the DOM load event, so your code attaches the event listener too late.

To fix this, set runAt to document_start. This works for me:

chrome.tabs.create({url: "https://mozilla.org"}, function (tab) {
    chrome.tabs.executeScript(tab.id, {
        code: "window.addEventListener('load', function(){alert('plop') },false);",
        runAt: "document_start"
    });
 });

Note: The other answer suggests to use error handling, but this code should not set lastError.

1 Like

My thought. Thats why I asked

Are you 100% sure that ‘load’ hasn’t fired yet?

but


It does, if the permission to access "https://mozilla.org" is not specified in the package.json.

1 Like

My thought. Thats why I asked

Are you 100% sure that ‘load’ hasn’t fired yet?

If load hasn’t fired yet it should in the future. I was saying that load had already fired by the time the script was executed, not that it had not fired yet.

It does, if the permission to access “https://mozilla.org” is not specified in the package.json.

You’re right. I was assuming that he had host permissions for it in his manifest. If you don’t check for lastError though you should get a warning in your console about not checking it. I assumed that the OP checked for console errors.

2 Likes