How to interact with background.js from the popup?

前端 未结 3 689
無奈伤痛
無奈伤痛 2020-12-04 20:46

Is there any way to pass information between the popup.html (or popup.js) and a background script?

I\'d like the popup to display information from a user\'s account

3条回答
  •  忘掉有多难
    2020-12-04 21:04

    Use the chrome.extension API.

    You can send requests back and forth or even better use a port for continuous communication.

    The example I give will create a two way communication between the popup and background page that connect when the popup is opened up.

    Just create a socket.js file that is included in both the background page and the popup page. Then on each you can just declare:

    new Socket();
    

    Here is the implementation of socket.js:

    var Socket = function() {
        window.socket = this;
    
        this.port = chrome.extension.connect({name:"popupToBackground"});
    
        chrome.extension.onConnect.addListener(function(port) {
            if(port.name == "backgroundToPopup") {}
                else if(port.name == "popupToBackground") {
                window.socket.port = chrome.extension.connect({name:"backgroundToPopup"});
            }
            else {
                return;
            }
    
            port.onMessage.addListener(function(msg) {
                try {
                    window[msg.namespace][msg.literal][msg.method].apply(this, msg.args);
                }
                catch(error) {
                    // your failed action goes here.
                }
            });
        });
    };
    

    Make sure you make the generic method calls in the message listener work for you. I like the format I have given above - it is very robust. To send messages back and forth just post them to the socket:

    socket.post({ namespace: "myNamespace",
                  literal: "myLiteral",
                  method: "myMethod",
                  args: ["argOne", "argTwo"]
               });
    });
    

    So if this were executed from the popup page then the background page would call:

    window.myNamespace.myLiteral.myMethod(argOne, argTwo);
    

    To me this is a very nice reusable javascript object. You can even add specific prototype functions if you would like - this way its even easier to send messages:

    Socket.prototype = {
        sendOneTwo: function() {
            socket.post({ namespace: "myNamespace",
                          literal: "myLiteral",
                          method: "myMethod",
                          args: ["argOne", "argTwo"]
        });
    };
    

    Now all you have to say is:

    socket.sendOneTwo();
    

提交回复
热议问题