简体   繁体   中英

'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'));
        }
      });
}

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'));
        }
      });
}

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