我想从内容脚本传递一个已保存的变量到弹出页面,所以我可以简单地输出它。 例如,如果我的内容脚本有下列代码:如何将信息从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