开发者

How do I pass information from the Content_script to the popup page? (Chrome extensions)

I would like to pass a saved varliable from the content script to the 开发者_开发问答popup page, so I would be able to simply output it. For example, if my content script has the following code:

var x = 'abc';

I would like the popup title to be this varliable.


Couple ways to do this, I used the first one in my extension:

  1. localStorage. Use sendRequest({}) to pass a message with your variable to the background page, which will then save the variable to localStorage. Once that's done, your popup can access the variable like localStorage["x"]. (It has to go through the background page because at this time, content scripts cannot access localStorage)

  2. Plain requests. Pray that the popup is open, and try sending it a message from the content script with the variable in it. Note that this is not a good solution simply because the popup might not be open when you try to send it the variable.

Code Example for #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"] );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜