繁体   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