簡體   English   中英

在 chrome 擴展中,無法從內容腳本向后台腳本發送消息並獲得響應

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

請幫我弄清楚為什么沒有收到或回復此消息:

content.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);
});

背景.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') {
        sendResponse(user);
        return true;
    }
    return true;
});

清單.json 文件:

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

內容腳本中的“running this”控制台日志打印出來,“background.js running”控制台日志也打印出來,但其他控制台日志都沒有打印出來。

我已經嘗試從擴展文檔中復制/粘貼示例,但它不起作用,並詢問了每個可用的 AI,但我無法弄清楚為什么它不發送。

我的測試結果與您的說法相矛盾。

在此處輸入圖像描述

內容.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);
});

背景.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;
});

清單.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"
      ]
    }
  ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM