You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展中如何将Popup的滑块值传递到Content脚本?

解决Popup滑块数值传递到Content脚本的问题

问题根源分析

  • manifest.json的content_scripts错误引入了popup.js,应为content.js
  • popup.js中sendPercentage函数的this.percentage存在引用错误,箭头函数与普通函数的上下文不匹配
  • 使用chrome.runtime.sendMessage无法直接向content脚本发消息,需改用chrome.tabs.sendMessage指定当前活跃标签页

修正后的代码

1. manifest.json

{
  "manifest_version": 3,
  "name": "PDF Dimmer",
  "description": "Dim brightness of pdf",
  "version": "1.0.0",
  "icons": {
    "48": "assets/icon48.png",
    "128": "assets/icon128.png"
  },
  "action": {
    "default_popup": "index.html"
  },
  "permissions": ["storage", "activeTab"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "css": ["styles/styles.css"],
      "js": ["scripts/content.js"],
      "run_at": "document_end"
    }
  ]
}
  • 移除不必要的nativeMessaging权限
  • 修正content_scripts的JS文件路径为content.js

2. popup.js

const slider = document.getElementById("myRange");

function sendPercentage(percentage) {
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, {'percentage': percentage});
  });
};

const updatePercentage = () => {
  const percentage = slider.value / 100;
  sendPercentage(percentage);
};

slider.addEventListener("change", updatePercentage);
  • 用const声明变量避免全局污染
  • 通过chrome.tabs.query获取当前活跃标签,再用chrome.tabs.sendMessage精准发送消息
  • 直接传递计算后的percentage参数,规避this指向问题
  • 简化事件监听逻辑

3. content.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    const percentage = request.percentage;
    if (window.location.href.endsWith(".pdf")) {
      const embed = document.getElementsByTagName("embed")[0];
      if (embed) {
        embed.style.filter = `brightness(${percentage})`;
      }
    }
  }
);
  • 增加embed元素存在性判断,避免页面无目标元素时报错
  • 使用模板字符串简化样式拼接逻辑

内容的提问来源于stack exchange,提问作者Menno Veerkamp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:22:46