React Chrome 擴充功能:從 popup.tsx 發送訊息到內容腳本錯誤
P粉549412038
P粉549412038 2024-04-01 09:13:33
0
1
357

我正在嘗試做一個 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粉549412038
P粉549412038

全部回覆(1)
P粉366946380

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!