将消息从 background.js 传递到 popup.js [英] Passing message from background.js to popup.js

查看:52
本文介绍了将消息从 background.js 传递到 popup.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我的 manifest.json 文件:

{
    "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"]
    }
}

我在 background.js

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');
        }
    }

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

My message listener in popup.js (from chrome extension samples)

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"});
  });

我得到的唯一错误是

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

Port error: Could not establish connection. Receiving end does not exist.

感谢您的帮助!

推荐答案

Popup 没有 tab id 所以你会得到错误.

Popup doesn't have tab id so you will get the error.

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

You can use chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener in that case.

所以在background.js

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

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)
        }
    }
);

希望对你有帮助.

谢谢,

这篇关于将消息从 background.js 传递到 popup.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆