30

我正在尝试实现我自己的 chrome 扩展,在某个事件上,创建浏览器通知并使用在 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"]
    }
}

我的sendMessage呼唤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 扩展示例)

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

我得到的唯一错误是

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

谢谢您的帮助!

4

5 回答 5

37

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

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

所以在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)
        }
    }
);

我希望它对你有帮助。

谢谢,

于 2017-04-19T03:25:33.363 回答
11

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

popup.js

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

背景.js

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

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

于 2016-08-22T08:44:14.830 回答
1

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

1)使用存储

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

背景.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

<html>    
<head>
    <script src="popup.js"></script>
</head>    
<body>
    <p id="popupElement1"></p>
    <p id="popupElement2"></p>
</body>    
</html>

清单.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"
    ]
}

2) 使用 chrome.runtime.sendMessage()

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

背景.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: "xxx" }, function (res) {
    document.getElementById("popupElement1").innerText = res.method;
    document.getElementById("popupElement2").innerText = res.data;
return true;
});

popup.html & manifest.json和第一个例子一样

于 2020-11-07T21:00:38.170 回答
0

用于runtime.sendMessage将消息发送到后台脚本,以及tabs.sendMessage从后台到内容脚本。

请注意,您需要指定标签 ID:

chrome.tabs.query({ active: true }, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, { greeting: 'hello' }, (response) => {
        console.log(response);
    });
});

您可以在此处找到完整的示例和文档:https ://developer.chrome.com/extensions/messaging#simple

于 2017-01-26T15:09:40.487 回答
0

本地存储解决方案

因为弹出窗口没有持久状态,您可能希望使用 localStorage 来存储弹出窗口状态并在弹出窗口打开时预加载它,并在弹出窗口打开时storage跟踪状态更改。

背景:

localStorage.setItem('popupData', JSON.stringify({ tabReady: true }));

弹出:

// Load the state from localStorage when popup opens
let popupData = JSON.parse(localStorage.getItem('popupData'));

// Keep track of changes to the popup state while the popup is open
window.addEventListener('storage', (e) => {
  if (e.key === 'popupData') {
    popupData = JSON.parse(e.newValue);
    console.log(popupData.tabReady);
  } 
});
于 2021-06-22T07:53:50.443 回答