Angelina Tsuboi
Angelina Tsuboi

Reputation: 326

'addEventListener' not working on Chrome Extension

I added an addEventListener to my window, but it is returning the following errors:

Uncaught TypeError: Failed to execute 'addEventListener' on 'EventTarget': 2 arguments required, but only 1 present. at

window.addEventListener('DOMContentLoaded', setUpStuff, false);

Another error:

Uncaught TypeError: Cannot read property 'addEventListener' of null (at:

 optionsButton.addEventListener('click', function() {

Here is the code:

window.addEventListener('DOMContentLoaded', setUpStuff, false);
function setUpStuff(){
    let optionsButton = document.getElementById('#go-to-options');
    optionsButton.addEventListener('click', function() {
        if (chrome.runtime.openOptionsPage) {
          chrome.runtime.openOptionsPage();
        } else {
          window.open(chrome.runtime.getURL('options.html'));
        }
      });
}

Upvotes: 1

Views: 2490

Answers (1)

Talmacel Marian Silviu
Talmacel Marian Silviu

Reputation: 1736

You are supposed to add an event on the execution of which the function is going to be run. And getElementById takes an ID, not a selector, so you need to remove the #:

window.addEventListener('DOMContentLoaded', setUpStuff, false);
function setUpStuff(){
    let optionsButton = document.getElementById('go-to-options');
    optionsButton.addEventListener('click', function() {
        if (chrome.runtime.openOptionsPage) {
          chrome.runtime.openOptionsPage();
        } else {
          window.open(chrome.runtime.getURL('options.html'));
        }
      });
}

Upvotes: 2

Related Questions