繁体   English   中英

从后台脚本中的 onMessage 侦听器记录

[英]Logging from onMessage listener in background script

在我的 Chrome 扩展程序中,我希望执行以下步骤:

  1. 单击触发弹出窗口的扩展程序图标后,将使用chrome.runtime.sendMessage发送一条消息。
  2. 该消息由后台脚本中的侦听器使用chrome.runtime.onMessage.addListener 这会触发一条消息记录到控制台

如果我在侦听器外部添加 console.log 命令,我会看到开发工具中记录的消息。

但是,我在监听器中的消息没有被记录下来,这让我相信没有收到消息。

我错过了什么吗?

代码:

清单.json

{
    "name": "xxx",
    "version": "1.0.0",
    "description": "xxx",
    "manifest_version": 3,
    "author": "xxx",
    "action":{
        "default_title": "xxx",
        "default_popup": "index.html"
    },
    "permissions": [
        "activeTab",
        "scripting"
    ],
    "background": {
        "service_worker": "background.js"
    }
}

背景.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log("listener");
});

脚本.js

chrome.runtime.sendMessage({message: "xxx"}, function(response) {
  console.log(response)
});

索引.js

<!DOCTYPE html>
<html>
<head>
    <title>xxx</title>
    <meta charset="utf-8">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-3" style="width: 450px;">
        <h2 class="text-center">Translation</h2>
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>a</th>
                <th>b</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td id="a"></td>
                <td id="b"></td>
            </tr>
            </tbody>
        </table>
    </div>
</body>
<script src="script.js"></script>
</html>

在我“更新”我的扩展程序之前,我在浏览器中刷新了 chrome://extension 页面后,这开始工作了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM