【发布时间】:2014-06-01 01:53:07
【问题描述】:
我已经多次阅读 Google 提供的有关“消息传递”的文档,并且可能已经查看了 10 多个具有相同问题的其他问题,并且已经尝试过对其大多数“解决方案”的一些变体以及什么我有下面...这是黑魔法,对吧?无论哪种方式,都可以。
清单文件:
{
"manifest_version" : 2,
"name" : "Message Test",
"version" : "1.0",
"browser_action": {
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches" : ["<all_urls>"],
"js": ["message-test.js"]
}
]
}
我知道扩展不应该使用内联 JS,但我将其保留,因此可以保留原来的问题,因为我仍然无法从后台页面发送消息,当我从弹出窗口切换到后台时,我从 manifest.json 中删除了相应的行
popup.html 文件:
<html>
<head>
<script>
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
console.log(response.farewell);
});
});
</script>
</head>
<body>
</body>
</html>
或
background.js 文件:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello", theMessage: "Why isn\'t this working?"}, function(response) {
console.log(response.farewell);
});
});
message-test.js 文件:
var Mymessage;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.greeting == "hello"){
Mymessage = message.theMessage;
alert(Mymessage);
}
else{
sendResponse({});
}
});
我收到一个未定义的警报...
在按下弹出窗口中的按钮并在指定的 url 处有一个窗口后,我也尝试执行此操作,但这是稍后的问题。按钮和窗口的其他文件可以在这里找到,除了 background.js 内容包含在 addEventListener("click"....: http://pastebin.com/KhqxLx5y 和 http://pastebin.com/JaGcp6tj
【问题讨论】:
-
all_urls 语法无效
-
@ZigMandel 碰巧就是这样。
-
@hucuhy 感谢您提出这个问题。自今天(2014 年 6 月 3 日)发布此消息以来,我仍未收到有用的回复。在点击默认弹出窗口中的按钮后,能够从后台页面向内容脚本发送消息对于知道这些东西如何工作的人来说似乎并不难......
标签: javascript google-chrome google-chrome-extension message-passing