我創建了一個由manifest.json,content.js和background.js組成的擴展。在content.js中,我提取當前標籤的URL並在background.js中打開一個新標籤。我想要做的,不起作用的是從內容傳遞URL並將其附加到我在後臺調用的URL。鉻擴展,將數據從內容傳遞到背景
content.js:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse)
{
if(request.greeting=="gimmieyodatas")
{
var output ="URL=";
//check for the character '?' for any parameters in the URL
var paramIndex = document.URL.indexOf("?");
//if found, eliminate the parameters in the URL
if (paramIndex > -1)
{
output += document.URL.substring(0, paramIndex);
};
sendResponse({data: output});
}
else{
sendResponse({});
}
});
background.js:
var output2;
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {greeting:"gimmieyodatas"}, function(response) {
output2 = response.data;
});
});
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.create({url: "http://www.google.com?" + output2}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "content.js"}, function() {
sendMessage();
});
});
});
當我運行從一個打開的選項卡擴展,它會打開谷歌的新選項卡上,但它並不追加Google網址中當前標籤的網址,這意味着「輸出」數據不會傳遞到background.js。我究竟做錯了什麼?
由於猶大書。我做了你所建議的一個區別。爲了確保在後臺處理'chrome.extension.onMessage.addListener',我添加了'output2 + =「this = test」',這樣它至少會返回'http://www.google.com?this =測試」。但是我得到'http://www.google.com'未定義',這意味着onMessage.addListener沒有經過。爲什麼?! –
好吧......我的壞!我剛剛意識到我忘了從content.js中刪除'chrome.extension.onMessage.addListener',那就是問題所在。非常感謝Jude解決我的問題... –
沒有問題。如果能解決您的問題,請接受/提高我的答案?乾杯。 –