我正在开发一个 Chrome 扩展程序,我的要求是在页面上为每个打开的选项卡创建元素(按钮),并希望在单击按钮时显示简单的警告消息。它适用于所有人,但它总是会导致 Gmail 出现问题, Facebook 和 Stackoverflow..请帮我解决这个问题。
我的内容脚本中有向网页添加按钮的代码。
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);
} ..... ..... ....
我认为是某些 Gmail 安全功能造成了这个问题。
最佳答案
document.body.innerHTML += /* ... */
我认为这是您的问题。它迫使 Chrome 重新创建 body
的整个 DOM,丢失附加的事件/数据。
正确的方法是构造并附加一个 DOM 节点:
var button = document.createElement("button");
button.id = "my_button";
button.className = "buttonCss";
button.textContent = "Show Button";
document.body.appendChild(button);
关于javascript - 内容脚本创建的元素在页面上创建 Gmail、Facebook、stackoverflow 等问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27622032/