简体   繁体   English

将带有选中复选框 ID 的消息从 popup.js 发送到 background.js

[英]Send message with ID of checked checkbox from popup.js to background.js

I want to send an ID of the checked checkbox from popup.js to background.js.我想将选中复选框的 ID 从 popup.js 发送到 background.js。 I tried it on the following way, but failed:我按以下方式尝试过,但失败了:

popup.html弹出窗口.html

<form id="cbx">
<label for="cb1">G</label>
<input name="cb1" type="checkbox">
<input type="submit" value="Submit">

popup.js弹出窗口.js

document.getElementById('cbx').addEventListener(

    'submit', function checkForm(event) {

    event.preventDefault();

    //Define the form element
    var form = document.getElementById("cbx");

    if (form.cb1.checked) {

chrome.runtime.sendMessage({greeting: "cb1"});

    }

    return true;

});

background.js背景.js

chrome.extension.onMessage.addListener(function (request, sender, sendResponseParam) {
if( request.greeting === "cb1" ){
    console.log("cb1"); 
}
})

After checking of the checkbox console remains empty.检查复选框后控制台仍然为空。 How can i handle this correctly?我该如何正确处理?

finally got in on this way:终于走上了这条路:

popup.js: popup.js:

    if (form.cb1.checked) {
chrome.runtime.sendMessage({greeting: "cb1"}, function(response) {
return true;
});
    }

background.js背景.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {

    if (request.greeting == "cb1"){
      sendResponse();
      console.log(request.greeting);
      var action_url = "http://www.google.com/";
    chrome.tabs.create({ url: action_url });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM