Upon receiving a message from a content script I want to create a new tab and fill the page it opens dynamically (for now I'm just trying to turn the newly created page red).
eventPage.js:
// ... code that injects another content script, works fine
// Problem code...
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse)
{
chrome.tabs.create({url: chrome.extension.getURL("blankpage.html")},
turnTabRed);
});
function turnTabRed(tab)
{
chrome.tabs.executeScript(
tab.id,
{code: 'document.body.style.backgroundColor="red"'}
);
}
This successfully creates a new tab and loads blankpage.html
(which is just an HTML page with some text) fine, but fails to paint the background colour red. After inserting console.log()
statements in various places and fooling around in the debugger, I have ascertained that turnTabRed
is being called, tab.id
is indeed the ID of the newly created tab and if I call document.body.style.backgroundColor="red"
from the console, the background of the new tab turns red. I noticed that if I added
(*)
chrome.tabs.query(
{}, function (tabArr) { for (var i = 0; tabArr[i]; i++)
console.log(tabArr[i].title); });
into the body of turnTabRed
the title of the new tab would not be printed into the console, which suggested that the script was being injected too early, so I tried delaying the injection with setTimeout
and when that failed, I tried listening for the status-complete event:
function turnTabRed(tab)
{
chrome.tabs.onUpdated.addListener(
function(tabUpdatedId, changeInfo, tabUpdated)
{
if (tabUpdatedId == tab.id && changeInfo.status &&
changeInfo.status == 'complete')
chrome.tabs.executeScript(
tabUpdatedId,
{code: 'document.body.style.backgroundColor="red"'});
});
}
which also failed. Calling (*) after waiting with setTimeout
did print the new tab's title along with all the others though.
What's wrong? How can I create a new tab, load an HTML page and then turn its background red?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…