简体   繁体   中英

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. I tried it on the following way, but failed:

popup.html

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

popup.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

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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