The element created by the script content on the page, creating a problem with Gmail, Facebook, stackoverflow, etc.

I am developing a Chrome extension, and my requirement is to create an element (button) on the page for each open tab and wants to show a simple warning message when the button is pressed .. it works correctly for everyone, but it always creates a problem with Gmail, Facebook and stackoverflow..please help me solve this problem.

I have a code to add a button to a webpage 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 are creating a problem.

+6
source share
1 answer
 document.body.innerHTML += /* ... */ 

I think this is your problem. This forces Chrome to re-create the entire DOM body , losing the attached events / data.

The correct way would be to create and add a DOM node:

 var button = document.createElement("button"); button.id = "my_button"; button.className = "buttonCss"; button.textContent = "Show Button"; document.body.appendChild(button); 
+1
source

Source: https://habr.com/ru/post/980082/


All Articles