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
.