处理关键事件,并通过chrome扩展名中的消息传递



我是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");
        });
    }
});

subtest.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);
    }
);

它只是在控制台上显示"书面"。不显示请求,在Console处发件人内容,也不输入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");
        });
    });
}

相关内容

  • 没有找到相关文章