Reputation: 13407
I'm trying to iterate over an array of URL's inside background.js
. For each URL, I want it to navigate the current tab, and then send a message to the content_script.js
telling it to perform an action.
The problem is it's sending it immediately and not when the page loads (in fact it sends it before even updating the URL)
background.js:
chrome.tabs.update(null, {
url: 'https://www.example.com/' + path
}, function(tab) {
chrome.tabs.sendMessage(tab.id, {message: 'update_user'});
});
content_script.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === 'update_user') {
console.log('loaded');
}
}
);
Upvotes: 2
Views: 3006
Reputation: 3302
if the async page load is your issue, something like this could help:
chrome.tabs.update(null, {
url: url
}, function (tab) {
chrome.tabs.onUpdated.addListener(function listener (tabId, info) {
if (info.status === 'complete' && tabId === tab.id) {
chrome.tabs.onUpdated.removeListener(listener);
chrome.tabs.sendMessage(tab.id, {message: 'update_user'});
}
});
});
});
This adds a separate listener to onUpdated
for each of the bad URLs. Each listener is only good for the single tab that was explicitly opened so there is no chance of "accidents".
Once the tab is loaded the listener is removed and the message is sent.
Upvotes: 4