3

I am aware that because of Chrome's csp, I can't execute inline JavaScript. I have an html file called popup.html which contains this:

 <body> <a href="#" id="clickme">Button</a> </body> 

and an external JavaScript file called chrome.js which contains this code:

document.addEventListener('DOMContentLoaded', init()); function init(){ var elem = document.getElementById('clickme'); elem.addEventListener('click',func()); } function func(){ alert('button clicked'); } 

Whenever I reload the Chrome extension, or click the extension Icon, func() gets fired, but when I click the actual button that the listener is subscribed to (Button), nothing happens. I have looked at the debugger using "inspect popup" and using location.reload() in the console, it seems as though elem is correctly set via getElementById(), but the event is immediately fired upon reloading the page, instead of when the link is clicked.

How can I make the event fire on click instead of on pageload?

1 Answer 1

2

Passing a function to an event listener like this document.addEventListener('DOMContentLoaded', init());

the function is immediately invoked.The correct way is to do this

document.addEventListener('DOMContentLoaded', init); 
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, you are passing a function result after invoking it. Do as this answer suggests or put the function inline as anonymous.
where i find out event name?
what if we had arguments in function ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.