【问题标题】:How to check popup.html page when action occurs within content.js (Chrome Extension)?在 content.js(Chrome 扩展程序)中发生操作时如何检查 popup.html 页面?
【发布时间】:2025-12-27 18:40:11
【问题描述】:

我的 chrome 扩展程序需要检查是否在该扩展程序处于活动状态的页面上选中了 popup.html 上的复选框。

content.js:

$(document).ready(function () {
  time = setInterval(function () {
    if(true){
      //check if checkbox is checked??
    }
  }, 500);
});

popup.html:

<!doctype html>
<html>
<head>
<input type="checkbox" name="thingToDo" value="isChecked"> Do thing<br>
</body>
</html>

有没有办法从 content.js 中抓取 popup.html?还是我需要一个 background.js 和某种来回发送的消息?

【问题讨论】:

  • 由于您将脚本注入网页,因此请避免使用计时器。只需将处理程序直接附加到复选框即可。 $('checkbox[name="thingToDo"]').change(...)
  • 您可以使用messaging API。

标签: javascript html google-chrome-extension


【解决方案1】:

popup.htmlcontent.js 之间不能直接通信,但通常的方式是使用chrome.storage API。

通过popup.html设置checked状态并监听content.js中的存储变化。

因此,无论何时或从何处更改存储值,您都将获得content.js

这也是一种简单且干净的方法。

【讨论】:

    最近更新 更多