-1

I have made a little extension which inserts buttons into the html page and I have inserted onClick events on each button, but when i press them they don't work. I have found some topics on this site and a guy was talking about addEventListener but i couldn't use it. My code is something like this:

var setButton = "<button type='button' id='setter2' onclick=Set_one(this.id)>set</button>";
var str = getRow.insertCell(-1);
str.innerHTML = setButton;
Xan
  • 74,770
  • 16
  • 179
  • 206
beso9595
  • 1,146
  • 3
  • 10
  • 16

1 Answers1

2

In Chrome extensions, inline code is forbidden. You cannot use onclick attribute at all for extension scripts, and CSP cannot be relaxed.

You will have to use addEventListener to make it work. It's not hard, and covered in the documentation linked above.

var setButton = "<button type='button' id='setter2' onclick=Set_one(this.id)>set</button>";
var str = getRow.insertCell(-1);
str.innerHTML = setButton;
document.getElementById("setter2").addEventListener("click", function() {
  Set_one(this.id);
});

It's even better though if you don't use innerHTML assignment and directly create/append elements:

var setButton = document.createElement("button");
    setButton.textContent = "set";
    setButton.id = "setter2";
    setButton.addEventListener("click", function() {
      Set_one(this.id);
    });
getRow.insertCell(-1).appendChild(setButton);
Xan
  • 74,770
  • 16
  • 179
  • 206