将消息从background.js传递给popup.js

Fra*_*rez 12 messaging google-chrome message-passing google-chrome-extension

我正在尝试实现我自己的chrome扩展,在某个特定事件上创建浏览器通知并使用background.js中计算的数据填充弹出窗口

这是mymanifest文件:

{
    "name": "Dummy name",
    "description": "Description",
    "manifest_version": 2,
    "version": "1.1.3",
    "icons": {
        "16": "icon_16.png",
        "48": "icon_48.png",
        "128": "icon_128.png",
        "256": "icon_256.png"
    },
    "browser_action": {
        "default_icon": "icon_48.png",
        "default_title": "Test",
        "default_popup": "popup.html"
    },
    "permissions": ["background","webRequest","webRequestBlocking","webNavigation","tabs","notifications"],
    "background": {
        "scripts":["jquery-1.8.1.min.js","classy.js","background.js"]
    }
}
Run Code Online (Sandbox Code Playgroud)

我在background.js中调用sendMessage

show : function(result) {
    var that = this;
    chrome.extension.sendMessage({greeting: "hello"}, function(response) {
        console.log(response);
    });

    if(window.webkitNotifications) {
        var notification = webkitNotifications.createHTMLNotification('notification.html');
        notification.show();
        setTimeout(function(){
            notification.cancel();
            }, '7000');
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在popup.js中的消息监听器(来自chrome扩展示例)

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });
Run Code Online (Sandbox Code Playgroud)

我得到的唯一错误是

端口错误:无法建立连接.接收端不存在.

谢谢您的帮助 !

Per*_*ect 19

弹出窗口没有标签ID,因此您将收到错误消息.

您可以使用chrome.runtime.sendMessage,并chrome.runtime.onMessage.addListener在这种情况下.

所以在background.js中

chrome.runtime.sendMessage({
    msg: "something_completed", 
    data: {
        subject: "Loading",
        content: "Just completed!"
    }
});
Run Code Online (Sandbox Code Playgroud)

并在popup.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.msg === "something_completed") {
            //  To do something
            console.log(request.data.subject)
            console.log(request.data.content)
        }
    }
);
Run Code Online (Sandbox Code Playgroud)

我希望它对你有所帮助.

谢谢,

  • 如果我打开了多个选项卡并向 popup.js 发送消息怎么办?哪个 popup.js 会收到它?如何将消息发送到我想要发送消息的地方@Perfect (2认同)

Aks*_*ngh 10

要解决这个问题,您需要首先向 background.js 发送握手消息,然后将 background.js 中的实际数据发送到 popup.js 例如:在我的情况下,我所做的是

弹出窗口.js

chrome.runtime.sendMessage({data:"Handshake"},function(response){
	
			});
chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
	str = JSON.stringify(message.data);
});
Run Code Online (Sandbox Code Playgroud)

背景.js

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
//alert(message.data);
	chrome.runtime.sendMessage({data:datax},function(response){
			});
			});
Run Code Online (Sandbox Code Playgroud)

我想要做的是,一旦我们点击图标,握手消息就会发送到 background.js,当它收到它时,我们就可以发送变量或我们想要在 popup.js 上发送的任何数据来呈现它在 popup.html 上。


jlo*_*jlo 9

这是我发现的将数据从 background.js 发送到 popup.js 的两种最简单的方法:

1)使用存储

将值保存到存储中,一旦打开弹出窗口,它就会从存储中获取值并将其显示在弹出窗口中。

背景.js

chrome.storage.sync.set({ 'dataValue1': 'Some data 1.' });
chrome.storage.sync.set({ 'dataValue2': 'Some data 2.' });
Run Code Online (Sandbox Code Playgroud)

弹出窗口.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);
Run Code Online (Sandbox Code Playgroud)

弹出窗口.html

<html>    
<head>
    <script src="popup.js"></script>
</head>    
<body>
    <p id="popupElement1"></p>
    <p id="popupElement2"></p>
</body>    
</html>
Run Code Online (Sandbox Code Playgroud)

清单.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": [
        "<all_urls>",
        "storage",
        "tabs"
    ]
}
Run Code Online (Sandbox Code Playgroud)

2)使用 chrome.runtime.sendMessage()

弹出窗口打开后,您可以从弹出窗口向后台发送一条消息以建立连接/握手(否则,如果您尝试发送消息,您将收到“未检查的运行时.最后错误:无法建立连接。接收端不存在。”从背景到弹出窗口并且弹出窗口未打开)。建立连接后,您可以从后台使用 sendResponse 将您想要发送到弹出窗口的数据首先发送。

背景.js

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

弹出窗口.js

chrome.runtime.sendMessage({ method: "getStatus", data: "xxx" }, function (res) {
    document.getElementById("popupElement1").innerText = res.method;
    document.getElementById("popupElement2").innerText = res.data;
return true;
});
Run Code Online (Sandbox Code Playgroud)

popup.html 和 manifest.json 与第一个示例中的相同