1

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?

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

I think it should be addEventListener('click', onButtonClicked); otherwise, the action function will be called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.