Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element created by Content script on page creating issue with Gmail,Facebook,stackoverflow etc

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.

like image 977
Rohit Dubey Avatar asked Dec 23 '14 14:12

Rohit Dubey


1 Answers

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);
like image 59
Xan Avatar answered Oct 15 '22 08:10

Xan