2013-06-21 24 views
0

我創建了一個由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。我究竟做錯了什麼?

回答

1

問題是,當打開新選項卡時,您沒有告訴後臺頁面發送消息。對chrome.tabs.getSelected的調用僅在擴展第一次運行時發生 - 每次打開新選項卡時都不會發生。

你在正確的軌道上通過使用背景頁面作爲兩個內容頁之間的中介,但我建議一個不同的方法:每一個新的標籤頁打開時

加載內容腳本,通過清單文件:

"content_scripts": [ 
    { 
     "matches" : [ 
      "<all_urls>" 
     ], 
     "js" : [ 
      "content.js" 
     ] 
    } 
], 

使用,只需將消息發送到與當前URL頁面的背景,只要加載一個簡單得多的內容腳本:

(content.js)

var paramIndex = document.URL.indexOf('?'); 
if (paramIndex > -1) { 
    chrome.runtime.sendMessage({output2: 'URL=' + document.URL.substring(0, paramIndex)}); 
} 

當背景頁面接收它保存URL到一個全局變量消息:

(background.js)

var output2; 
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { 
    output2 = request.output2; 
}); 

點擊操作按鈕時,您可以然後加載URL :

(background.js)

chrome.browserAction.onClicked.addListener(function() { 
    chrome.tabs.create({url: "http://www.google.com?" + output2}); 
}); 
+0

由於猶大書。我做了你所建議的一個區別。爲了確保在後臺處理'chrome.extension.onMessage.addListener',我添加了'output2 + =「this = test」',這樣它至少會返回'http://www.google.com?this =測試」。但是我得到'http://www.google.com'未定義',這意味着onMessage.addListener沒有經過。爲什麼?! –

+1

好吧......我的壞!我剛剛意識到我忘了從content.js中刪除'chrome.extension.onMessage.addListener',那就是問題所在。非常感謝Jude解決我的問題... –

+0

沒有問題。如果能解決您的問題,請接受/提高我的答案?乾杯。 –

相關問題