最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding Click Event to a Button in a Chrome Extension - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question edited Oct 18, 2018 at 17:48 Serhat Koroglu asked Oct 18, 2018 at 17:41 Serhat KorogluSerhat Koroglu 1,2754 gold badges19 silver badges42 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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./js/js_htmldom.asp

EDIT: spelling

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.

发布评论

评论列表(0)

  1. 暂无评论