I am developing a Chrome extension and my requirement is to create element(button) on page for each tab open and wants to show simple alert message on clicking button..it works properly for all but it always creating issue with Gmail,Facebook and Stackoverflow..please help me to resolve this issue.
I am having the code of adding button to a web page in my Content script.
manifest.json
....
....
"content_scripts": [
{
"matches":["http://*/*", "https://*/*"],
"css": [ "style.css" ],
"js":["contentScript.js"],
"all_frames": false,
"run_at": "document_idle"
}
]
....
....
contentScript.js
....
....
function addButton() {
document.body.innerHTML += '<button id="my_button" class="buttonCss">Show Button</button>';
var button = document.getElementById("my_button");
button.addEventListener("click", function () {
alert("hello");
}, false);
} ..... ..... ....
I think some Gmail security features is creating the issue.
document.body.innerHTML += /* ... */
I think this is your issue right there. It forces Chrome to re-create the entire DOM of body
, losing attached events/data.
The proper way would be to construct and append a DOM node:
var button = document.createElement("button");
button.id = "my_button";
button.className = "buttonCss";
button.textContent = "Show Button";
document.body.appendChild(button);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With