簡體   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