我对 Chrome 扩展程序开发非常陌生,我想做一些 super 简单的事情,但我不确定为什么它不起作用。 本质上,我想:
- 运行 popup.js 脚本,以编程方式注入(inject)脚本
- 让注入(inject)的脚本从事件选项卡获取一些数据
- 使用 chrome.runtime.sendMessage 将数据发送回 popup.js
- 在 popup.js 中收到数据时执行某些操作(例如,在扩展程序弹出窗口中显示事件选项卡的 URL)
我的 list 中的权限是“activeTab”、“storage”、“tabs”。
这是我尝试用于测试目的的代码
popup.js
chrome.tabs.executeScript(null, {file: "injected.js"});
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
console.log("message received!");
});
注入(inject).js
var url = "";
// get the url of the current tab
chrome.tabs.query({currentWindow: true, active: true},
function(tabs) {
url = tabs[0].url;
console.log("running");
});
chrome.runtime.sendMessage({"url": url});
问题是“消息已收到!”当我使用调试器时,永远不会打印到控制台,但是“运行”将打印得很好。我查看了似乎有类似问题的问题:
- Chrome Extension Message passing: response not sent
- Chrome extension : error when sending message back from injected script to background script
- Message Passing Example From Chrome Extensions
所有已接受的答案似乎都不适合我。我尝试将 return true;
添加到 onMessage 事件监听器,但它似乎不起作用。我在调试器的控制台上也没有收到任何错误(通过单击“检查弹出窗口”)。我觉得我错过了一些微不足道的东西,但我不知道它是什么。 onMessage 没有收到任何内容是否有原因?
最佳答案
documentation列出了内容脚本中允许的几个 chrome API,而不是 chrome.tabs
。
Solution: use
chrome.tabs
in a privileged page like the popup.
与所有带有回调函数的 Chrome API 一样,chrome.tabs.query
是 asynchronous并在执行当前函数/上下文后调用回调。因此下一条语句只会看到旧的 url
(空字符串)。
Solution: process the received data right in the callback.
因此,在您的场景中,根本不需要内容脚本以及 “tabs”
权限,如 "activeTab" documentation 中所示。 :它会在用户手势(例如单击扩展工具栏弹出窗口)后自动设置临时权限。
关于javascript - Chrome 扩展 - 弹出窗口中的 onMessage 未收到来自注入(inject)脚本的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131889/