我想從內容腳本傳遞一個已保存的變量到彈出頁面,所以我可以簡單地輸出它。 例如,如果我的內容腳本有下列代碼:如何將信息從Content_script傳遞到彈出頁面? (Chrome擴展)
var x = 'abc';
我想彈出標題是這個varliable。
我想從內容腳本傳遞一個已保存的變量到彈出頁面,所以我可以簡單地輸出它。 例如,如果我的內容腳本有下列代碼:如何將信息從Content_script傳遞到彈出頁面? (Chrome擴展)
var x = 'abc';
我想彈出標題是這個varliable。
夫婦方法可以做到這一點,我用我的擴展的第一個:
localStorage
。使用sendRequest({})
將帶變量的消息傳遞給後臺頁面,然後將該變量保存到localStorage
。完成後,彈出窗口可以訪問像localStorage["x"]
這樣的變量。 (它必須經過後臺頁面,因爲目前內容腳本無法訪問localStorage
)
普通請求。祈禱彈出窗口處於打開狀態,並嘗試從內容腳本發送一條消息,其中包含變量。請注意,這不是一個好的解決方案,因爲當您嘗試將變量發送給它時,彈出窗口可能不會打開。
代碼例1:
//sendRequests look like this: sendRequest(message - Object, [callback - Function]);
//API Docs:
//onRequest Listener: http://code.google.com/chrome/extensions/extension.html#event-onRequest
//sendRequest Method: http://code.google.com/chrome/extensions/extension.html#method-sendRequest
//localStorage: http://www.html5rocks.com/features/storage
//From the Content Script
//Send request to background.html, no callback
chrome.extension.sendRequest({
type: "popup_var", /* In my extensions, because I could often be different types of reqeusts, I use a type variable to identify them */
my_variable: "Sally sold seashells by the seashore" /* Whatever variable you are trying to send */
});
//In background.html
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse){
if(request.type == "popup_var"){
/* The type of message has been identified as the variable for our popup, let's save it to localStorage */
localStorage["popup_var"] = request.my_variable;
}
}
);
//In popup.html
console.log("Variable from Content Script: "+localStorage["popup_var"]);
彈出的並不總是開放的,相反的背景頁面始終可用。 'popup title'是什麼意思? – pimvdb 2011-03-21 12:41:36
它不一定是它的標題。它可以是任何類型的文本...我只是想在彈出框內輸入這個varlible作爲一個字符串。 – Ariel 2011-03-21 12:55:57