首頁  >  問答  >  主體

React Chrome 擴充功能:從 popup.tsx 發送訊息到內容腳本錯誤

我正在嘗試做一個 chrome 擴展,我想透過點擊 popup.tsx 的按鈕來傳送訊息到內容腳本,但我收到此錯誤: 錯誤處理回應:TypeError:無法讀取未定義的屬性(讀取「再見」)

這是我的程式碼:

按鈕元件:

    function TWCredibility() {
      const ValidateTwitterTweets = () => {
        // Send message to content script to perfom Twitter Api validation
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.sendMessage(
            tabs[0].id as number,
            { sender: "www", instruction: "api" },
            function (response) {
              alert(response.farewell);
            }
          );
        });
      };
    
      return (
        <div id="PageSensitiveButtons" className="flex justify-center">
          <button
            id="VerifyPageButtonTwitterApi"
            type="submit"
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
            onClick={ValidateTwitterTweets}
          >
            Verify Page Tweets with Twitter Api
          </button>
        </div>
      );
    }

Popup.tsx:

const Popup = () => {

  return (
    <div className="container max-h-60 p-2.5 w-[480px]">
      <h2 className="title text-3xl font-bold my-1 text-center py-2">
        T-CREo v2.0.0
      </h2>

      {/* Plain Text Credibility */}
      <PlainTextCredibility />

      <hr id="firstHorBar" className="my-2.5" />
      <h6 id="currentPage" className="flex justify-center text-base">
        {" "}
      </h6>

      {/* TW Credibility */}
      <TWCredibility />

      {/* Spinner */}
    </div>
  );
};

內容腳本:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  // If sender is 'www' and instruction is 'api', then scraping
  if (msg.sender === "www" && msg.instruction === "api") {
    console.log("Message received from www");
    alert("Message received from www");
    sendResponse({ farewell: "to-do" });
  }
});

清單 v3:

{
    "manifest_version": 3,
    "name": "T-CREo v2.0",
    "description": "sí",
    "version": "1.0.0",
    "action" : {
        "default_popup": "popup.html",
        "default_title": "T-CREo v2.0",
        "default_icon" : "icon.png"
    },
    "permissions": [
        "activeTab",
        "background",
        "contextMenus",
        "declarativeContent",
        "tabs",
        "storage",
        "scripting"
    ],
    "icons": {
        "16" : "icon.png",
        "48" : "icon.png",
        "128" : "icon.png"
    },
    "options_page": "options.html",
    "background": {
        "service_worker": "background.js"
    },
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["contentScript.js"]
        }
    ]
}

我得到的錯誤: Chrome 擴充功能出錯

P粉549412038P粉549412038172 天前281

全部回覆(1)我來回復

  • P粉366946380

    P粉3669463802024-04-02 00:47:53

    更新擴充功能後您是否刷新了選項卡?您是否也嘗試在 HTTP/HTTPS 網站上開啟擴充功能?

    回覆
    0
  • 取消回覆