DOM修改弹出窗口或标签在chrome扩展立即撤消一旦脚本完成

DOM modifications to popup or tab in chrome extension instantly undone once script completes

本文关键字:撤消 脚本 扩展 chrome 修改 窗口 标签 DOM      更新时间:2023-09-26

单击BrowserAction时,test.html在新选项卡中打开。这工作如预期。这里是background.js:

chrome.browserAction.onClicked.addListener(function () {
  chrome.tabs.create({
    url: "./test.html"
  });
});

这里是test.html:

<!DOCTYPE HTML>
 <head>
 </head>
 <body>
  <form>
   <fieldset id="top">
    <button id="clickme">click me</button>
   </fieldset>
   <fieldset id="bottom">
   </fieldset>
  </form>
  <script src="test.js"></script>
 </body>
</html>

test.html调用test.js:

console.log("checking in");
document.getElementById("clickme").onclick = function () {
 var newButton = document.createElement("button");
 newButton.textContent = "now click me";
 newButton.onclick = function () {
  document.getElementById("bottom").style.backgroundColor = "pink";
 };
 document.getElementById("bottom").appendChild(newButton);
 alert("I'm an alert. If you comment me out, the tab will revert to its unmodified state, probably before you even see the second button.");
};

新按钮出现,但一旦警报被清除就会消失。我发现对扩展中打开的选项卡或弹出窗口所做的DOM修改总是在脚本完成后立即恢复到原始状态。有办法让其中一个不动吗?

您的<form>在点击时重新提交,在没有操作url的情况下,它只是重新加载页面。

要么根本不使用<form>,要么使用适当的onsubmit事件侦听器,要么在所有单击侦听器中添加event.preventDefault();,要么将type="button"添加到所有按钮中。