简体   繁体   中英

Logging from onMessage listener in background script

In my Chrome Extension, I want the following steps to execute:

  1. Upon clicking the extension icon which triggers a popup, a message is sent using chrome.runtime.sendMessage .
  2. The message is received by a listener in the background script using 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.

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

{
    "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

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

script.js

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

index.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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