camstar915
camstar915

Reputation: 153

In a chrome extension, can't send a message from the content script to the background script and get a response

Please help me figure out why this message is not getting received or responded to:

content.js file:

console.log('running this');
chrome.runtime.sendMessage({
    greeting: 'get-user-data'
}, (response) => {
    // 3. Got an asynchronous response with the data from the service worker
    console.log('received user data', response);
});

background.js file:

console.log('background.js running');
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Message received: ', message);
    // 2. A page requested user data, respond with a copy of `user`
    if (message.greeting === 'get-user-data') {
        sendResponse(user);
        return true;
    }
    return true;
});

manifest.json file:

{
  "manifest_version": 3,
  "version": "1.0",
  "action": {
    "default_popup": "index.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": [
        "https://*.myshopify.com/*"
      ],
      "js": [
        "content.js"
      ],
      "run_at": "document_idle"
    }
  ],
  "permissions": [
    "storage",
    "activeTab",
    "tabs",
    "https://*.com/admin/orders/*",
    "scripting",
    "webRequest"
  ]
}

The "running this" console log in the content script prints, and the "background.js running" console log also prints, but none of the other console logs get printed.

I've tried copy/pasting in the example from the extensions docs and it doesn't work, and asked every AI available, but I can't figure out why it's not sending.

Upvotes: 0

Views: 2730

Answers (1)

Norio Yamamoto
Norio Yamamoto

Reputation: 1792

My test results contradict your claims.

enter image description here

cotent.js

console.log('running this');
chrome.runtime.sendMessage({ greeting: 'get-user-data' }, (response) => {
  // 3. Got an asynchronous response with the data from the service worker
  console.log('received user data', response);
});

background.js

console.log('background.js running');
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Message received: ', message);
  // 2. A page requested user data, respond with a copy of `user`
  if (message.greeting === 'get-user-data') {
    const user = "user";
    sendResponse(user);
    return true;
  }
  return true;
});

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": [
        "https://nory-soft.web.app/*"
      ],
      "js": [
        "content.js"
      ]
    }
  ]
}

Upvotes: 3

Related Questions