Passing message from background.js to popup.js

后端 未结 4 1483
无人共我
无人共我 2020-12-05 10:12

I\'m trying to implement my own chrome extension on which, on a certain event, create a browser notification and fills the popup with data calculated in background.js

<
4条回答
  •  执念已碎
    2020-12-05 11:06

    These are the two simplest ways I've found to send data from background.js to popup.js:

    1) Using storage

    Save values into storage and once popup gets opened, it gets the values from storage and displays them in the popup.

    background.js

    chrome.storage.sync.set({ 'dataValue1': 'Some data 1.' });
    chrome.storage.sync.set({ 'dataValue2': 'Some data 2.' });
    

    popup.js

    function updatePopup() {
        chrome.storage.sync.get(['dataValue1', 'dataValue2'], function (data) {
            document.getElementById("popupElement1").innerText = data.dataValue1;
            document.getElementById("popupElement2").innerText = data.dataValue2;
        });
    }    
    document.addEventListener('DOMContentLoaded', updatePopup);
    

    popup.html

        
    
        
        
    
        

    manifest.json

    {
        "name": "Background2popup",
        "version": "1.0",
        "manifest_version": 2,
        "description": "This is a demo",
        "browser_action": {
            "default_popup": "popup.html"
        },
        "background": {
            "scripts": [
                "background.js"
            ]
        },
        "permissions": [
            "",
            "storage",
            "tabs"
        ]
    }
    

    2) Using chrome.runtime.sendMessage()

    Once popup opens, you send a message from popup to background to establish the connection/handshake (otherwise, you would get a 'Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.' if you try to send a message from background to popup and popup isn't open). Once with the connection established, you use sendResponse from background to send the data you wanted to send to popup in the first place.

    background.js

    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
        if (request.method == "getStatus") {
            console.log(request.data)
            sendResponse({ method: "peepee", data: "poopoo" })
        }
    });
    

    popup.js

    chrome.runtime.sendMessage({ method: "getStatus", data: "fag" }, function (res) {
        document.getElementById("popupElement1").innerText = res.method;
        document.getElementById("popupElement2").innerText = res.data;
    return true;
    });
    

    popup.html & manifest.json are the same as in the first example

提交回复
热议问题