2013-03-15 143 views
4

您好我有Chrome擴展,內容腳本發送郵件事件到後臺頁面 我想修改郵件事件的彈出窗口頁面。背景頁面是空白的最初Chrome擴展程序 - 修改郵件事件的彈出頁面

我曾嘗試:

chrome.extension.onMessage.addListener(function (request, sender, sendResponse) { 
    console.log('message received'); 
    chrome.extension.getBackgroundPage().document.innerHTML = 'hello world'; 
} 

但是當我點擊擴展程序圖標它仍然是空白。你能幫我嗎? 我可以在控制檯中看到該消息已收到。

回答

8

彈出窗口,作爲擴展頁面,不是背景頁面。只有打開時纔可以訪問。因此,根據其他信息改變彈出頁面的最好方法是從彈出窗口本身啓動消息。我認爲你正在使用內容腳本來獲取頁面上的某種信息,然後根據該信息更改彈出窗口。您可以準備數據並在內容腳本本身擁有一個onMessage偵聽器,或者您可以將信息傳遞到後臺頁面並從彈出窗口請求。第一個例子是:

內容腳本

... 
//assume that you already have the info you want stored in 'info' 

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){ 
    sendResponse(info); 
}); 

彈出

chrome.tabs.query({'active': true,'currentWindow':true},function(tab){ 
    chrome.tabs.sendMessage(tab[0].id,"stuff", function(response){ 
    //assuming that info was html markup then you could do 
    document.body.innerhtml = response; 
    //I personally wouldn't do it like this but you get the idea 
    }); 
}); 

如這裏要求使用背景頁作爲中介它:

內容腳本

// same assumption that info is already defined as the info you want 
chrome.runtime.sendMessage({'method':'setInfo','info':info}); 

背景頁

var info; 
chrome.runtime.onMessage(function(message,sender,sendResponse){ 
    // When we get a message from the content script 
    if(message.method == 'setInfo') 
    info = message.info; 
    // When we get a message from the popup 
    else if(message.method == 'getInfo') 
    sendResponse(info); 
}); 

彈出

chrome.runtime.sendMessage({'method':'getInfo'},function(response){ 
    //response is now the info collected by the content script. 
    console.log(response); 
}); 

當然你也可以在後臺網頁存儲信息中不是簡單的全局變量更好的辦法。一個好方法是使用。

+0

感謝您的回覆。我要去試試 – emte 2013-03-18 09:10:07

+0

@BeardFist能否提供第二種情況的例子。 – 2013-05-01 06:06:20

+0

@RyanGrush我添加了你想要的例子。 – BeardFist 2013-05-01 06:46:57

相關問題