Reputation: 467
I want to write a small chrome extension which shall take an information from webpage A (current webpage), update the tab to webpage B and then inject code into webpage B. unfortunaetelly the following code is updating the webpage to B but injecting the code to webpage A. The code in background.html is:
chrome.tabs.update(tab.id,{url: "http://B.com"});
chrome.tabs.executeScript(tab.id, {file: "inject_into_B.com.js"}); /* injections goes misleadingly to webpage A*/
Upvotes: 2
Views: 5176
Reputation: 1268
You want something like this:
chrome.tabs.update(tab.id, {url: request.url, active: true}, function(tab1) {
// add listener so callback executes only if page loaded. otherwise calls instantly
var listener = function(tabId, changeInfo, tab) {
if (tabId == tab1.id && changeInfo.status === 'complete') {
// remove listener, so only run once
chrome.tabs.onUpdated.removeListener(listener);
// do stuff
}
}
chrome.tabs.onUpdated.addListener(listener);
});
Upvotes: 7
Reputation: 111335
chrome.tabs.update
is asynchronous call (like pretty much all others), so if you want to run those commands in order you need to use a callback function:
chrome.tabs.update(tab.id,{url: "http://B.com"}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "inject_into_B.com.js"});
});
Upvotes: 2