简体   繁体   English

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

[英]Logging from onMessage listener in background script

In my Chrome Extension, I want the following steps to execute:在我的 Chrome 扩展程序中,我希望执行以下步骤:

  1. Upon clicking the extension icon which triggers a popup, a message is sent using chrome.runtime.sendMessage .单击触发弹出窗口的扩展程序图标后,将使用chrome.runtime.sendMessage发送一条消息。
  2. The message is received by a listener in the background script using chrome.runtime.onMessage.addListener .该消息由后台脚本中的侦听器使用chrome.runtime.onMessage.addListener This triggers a message to be logged to the console这会触发一条消息记录到控制台

If I add a console.log command outside of the listener, I DO see the message logged in the dev tools.如果我在侦听器外部添加 console.log 命令,我会看到开发工具中记录的消息。

However, my message inside the listener is not logged, which leads me to believe the message is not being received.但是,我在监听器中的消息没有被记录下来,这让我相信没有收到消息。

Am I missing something?我错过了什么吗?

Code:代码:

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

background.js背景.js

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

script.js脚本.js

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

index.js索引.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>

This started working after I refreshed the chrome://extension page in my browser before I “updated” my extension.在我“更新”我的扩展程序之前,我在浏览器中刷新了 chrome://extension 页面后,这开始工作了。

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

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