使用 chrome 扩展中传递的消息处理 keyup 事件

Handling keyup event with message passing in chrome extension

我是 chrome 扩展开发的新手。我正在尝试创建一个由文本字段和按钮组成的扩展。如果用户在文本字段中输入一些文本,那么确切的内容应该自动输入 HTML 页面的登录 ID 字段。

这是我的文件..

Popup.html

<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key  
with
value "popup.html".
-->
<html>
  <head>
    <title>Email Extension</title>
    <script type="text/javascript" src="popup.js"></script>
  </head>

  <body>
  <center>
       Enter email id:
       <br>
       <br>
       <input type="text" id="txtEmail">
       <br>
       <br>
       <input type="button" id="btnClear" value=" Clear ">
    </center>
 </body>
</html>

Popup.js

 document.addEventListener('DOMContentLoaded', function() {
    var btnElement = document.getElementById("btnClear");
    var txtElement = document.getElementById("txtEmail");
    // onClick's logic below:
    btnElement.addEventListener('click', function() {
        clearField();
    });

    txtElement.addEventListener('keyup', function() {
        changeEmail();
    });

    function clearField() {
        txtElement.value = "";
    }

    function changeEmail() {
        var emailId = txtElement.value;
        chrome.runtime.sendMessage({msg:emailId}, function(response) {
            console.log("written");
        });
    }
});

manifest.json

{
  "manifest_version": 2,

  "name": "Email Extension",
  "description": "This extension allows the user to enter Email id for login.",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click to Enter user id"
  },

  "permissions": [
    "activeTab",
    "storage"
  ],

  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["myscript.js"]
    }
  ]
}

myscript.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        var email = document.getElementById("login_username");
        email.value = request.msg;
        console.log(request);
        console.log(sender);
        console.log(email.value);
    }
);

它只是在控制台上显示 "written"。不在控制台显示请求、发件人内容,也不在 login_username

中输入任何内容

任何人都可以帮助找出我哪里出错了吗?

您不能使用 chrome.runtime.sendMessage 向内容脚本发送消息。您必须将 chrome.tabs.sendMessage 与内容脚本为 运行 的选项卡的 ID 一起使用。例如,要将其发送到当前活动的选项卡,您可以使用类似:

function changeEmail(){
    var emailId = txtElement.value;
    chrome.tabs.query({active:true,currentWindow:true}, function(tabs){
        chrome.tabs.sendMessage(tabs[0].id,{msg:emailId}, function(response) {
            console.log("written");
        });
    });
}