我想将保存的varliable从内容脚本传递到弹出页面,所以我可以简单地输出它。 例如,如果我的内容脚本具有以下代码:
var x = 'abc';
我希望弹出标题是可变的。
答案 0 :(得分:2)
有几种方法可以做到这一点,我在扩展中使用了第一个:
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"] );