Reputation: 1259
I want to add click event to a button element which I added it dynamically within the chrome.tabs.onUpdated event function by running executeScript function.
chrome.tabs.onUpdated.addListener(() => {
chrome.tabs.executeScript(null, {file: "execute.js" });
})
I add a click event function to the dynamically added button element with this code inside executed execute.js file but it didn't work;
var btnComment=document.createElement('button');
btnComment.addEventListener('click',function(){
console.log('btnComment worked')
});
I use background.html page inside it request to background.js file. How can I implement this function?
Upvotes: 1
Views: 13074
Reputation: 305
Does your backround.html have this?
<script src="background.js"></script>
Note that you create your button in execute.js, but your html uses background.js so in your background.js file, you will need this:
function onButtonClicked (){
console.log('btnComment worked');
}
document.getElementById('button').addEventListener('click', onButtonClicked());
btw, I'm also still learning google chrome extensions.
Upvotes: 1
Reputation: 303
Unfortunately due to a lack of context in terms of what your program looks like I can't give a 100% sure answer. However, I believe the problem is that you need to specifically select the element first using the DOM.
try
document.getElementById('button').addEventListener('click',function(){
console.log('btnComment worked')
});
more info about the Document Object Model can be found here: https://www.w3schools.com/js/js_htmldom.asp
EDIT: spelling
Upvotes: 3