簡體   English   中英

如何在 Chrome 擴展程序中將數據從 popup.js 發送到 content.js

[英]How to send data from popup.js to content.js in a Chrome Extension

我正在制作一個 chrome 擴展程序,它將自動填充頁面上的輸入(在本例中為 outlook 主題行),我需要以某種方式將從 popup.js(擴展程序)的輸入中獲得的消息傳遞到content.js 以便我可以更新該頁面上的 DOM。

彈出窗口.html

<!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <input type="text" id="message" name="message" placeholder="Enter a message..." class="message-input">
        <input type="submit" value="Set new message" id="message-btn" class="message-btn">
    </div>
</body>
<script src="popup.js"></script>

</html>

彈窗.js

let messageInput = document.getElementsByClassName('message-input')[0];
let updateMessageBtn = document.getElementById('message-btn');

updateMessageBtn.addEventListener('click', async(messageInput) => {
        // Query tab
    let queryOptions = { active: true, currentWindow: true };
    let tabs = await chrome.tabs.query(queryOptions);

    // Open up connection
    const port = chrome.tabs.connect(tabs[0].id, {
        name: "uiOps",
    });

        port.postMessage({
            message: messageInput.value
        });

            port.onMessage.addListener(function(msg) {
        if (msg.exists) {
            alert('Exists');
        } else {
            alert("Doesn't exist");
        }
    })
});

內容.js

chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function (msg) {
    if (port.name === "uiOps") {
      const idToQuery = msg.message;
      if (idToQuery) {
        port.postMessage({
          exists: true,
        });
      } else {
        port.postMessage({
          exists: false,
        });
      }
    }
  });
});

清單.json

{
    "name": "Email Autofiller",
    "description": "Automatically fill email subject lines!",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": ["storage", "activeTab", "scripting"],
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
        "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
    },
      "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  }
}

我嘗試了很多不同的方法,包括嘗試使用 localstorage,但沒有用。 我認為我走在正確的軌道上,但 Google Chrome 擴展文檔讓我有些困惑。 任何幫助表示贊賞 - 謝謝!

我將嘗試為您提供一個具體示例。 首先,你需要修改你的manifest.json添加內容腳本

清單.json

   "content_scripts": [ // add this
      {
         "matches": [
            "<all_urls>"
         ],
         "js": ["content.js"]
      }
   ],

然后,在您的 content.js 文件中,您將編寫一個消息偵聽器。

內容.js

chrome.runtime.onMessage.addListener( // this is the message listener
    function(request, sender, sendResponse) {
        if (request.message === "autoFill")
            autoFill(request.textToFill);
    }
);

async function autoFill(textToFill){ // here write your function...
    console.log(textToFill)
}

您現在將從 popup.js 發送消息。

彈窗.js

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, 
        {
            message: "autoFill",
            textToFill: "some text" 
        }, function(response) {})
})

就是這樣!

如果您需要更多幫助或說明,請隨時發表評論。 祝你的項目好運!

暫無
暫無

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

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