Theo
Theo

Reputation: 23

Inserting a button into the DOM with an onclick event for Chrome extension

I'm doing some Christmas Eve coding and needed some help. I'm trying to create a Chrome extension where I can insert a button into the DOM after highlighting some text. The main core of the logic lies here:

var button = document.createElement('input');
button.type = 'button';
button.value = 'test';
button.setAttribute('id', 'bookmark-button');
button.setAttribute('style', 'position:fixed; top:' + top_coord + 'px; left: ' + mid_coord + 'px;');
document.body.appendChild(button);
button.addEventListener("click", function() {
  console.log('test');
  alert('hello');
});

I avoided the setAttribute way because I know you can't do inline Javascript in Chrome extension. Also, this code exists in my content script file.

The button appears, but when I click, nothing happens. Has anybody ran into this problem before?

Upvotes: 0

Views: 287

Answers (1)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19080

Checked your code, and it works pretty well on my side:

enter image description here

Maybe you have a z-index problem on the button or some script errors prevent the click handler execution.

Upvotes: 2

Related Questions