Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add event listener for checkbox in Chrome extension's popup?

I'm trying to capture changes of checkbox in popup of my Chrome Extension. Documentation says:

Inline JavaScript will not be executed

There is an example provided on the same page, but it for button. I don't know how to modify it so it would capture chekbox's state changes.

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('button').addEventListener('click', clickHandler);
});

Example

like image 783
Roman Avatar asked Jul 19 '12 00:07

Roman


People also ask

How do I add a listener to a checkbox?

To add a checkbox check event listener with JavaScript, we can listen for the change event. to add a checkbox. const checkbox = document. querySelector("input[name=checkbox]"); checkbox.

How do I add a pop up extension to Chrome?

So, to set your popup, you would call it like this: chrome. browserAction. setPopup({popup: "logged_in.

How do I add an event listener to multiple checkboxes?

Here's one approach to setting up event listeners on checkboxes. I used document. querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked.


1 Answers

Had the same problem but reference a very helpful site which list events in Javascript. After doing a quick search (Ctrl+F) for the keyword "check" I found the "change" event listed...supposedly compatible with most browsers. Sure enought it was there, so my assumption is that maybe there is a "change event" for checkboxes. Low and behold just test it and it seems to work. Here is your code revised a little and the link of events (http://help.dottoro.com/larrqqck.php):

Example of html from popup.html

    <div class="menu" >
<input type="checkbox" id="showAlert" name="showAlert"/>
<label for="showAlert"><nobr>Show Alert</nobr></label></div>

Example of code snippet from popup.js

document.addEventListener('DOMContentLoaded', function () {
      document.querySelector('#showAlert').addEventListener('change', changeHandler);
});

Of course you will need to pass this into a function like:

function changeHandler(){
   //Do Something...maybe another function showAlert(), for instance
   if(showAlert.checked){
      //do something
   }
   else{
      //do something else
   }
}

01/06/2018 - EDIT: I just glanced back at this article and it appears this is likely going to become deprecated. Hence forward you may wish to use the MutationObserver (https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).

like image 70
Richard Chassereau Avatar answered Oct 18 '22 14:10

Richard Chassereau