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

Manifest V2下Vite打包Chrome扩展executeScript传参问题

背景

我正在使用基于Vite的samrum/create-vite-plugin-web-extension开发Chrome扩展,希望在项目中通过executeScript实现从popup.js向脚本传递参数的功能。

如果不使用任何框架和打包工具,仅用原生JavaScript,我可以在Manifest V2中通过以下代码实现:

// 原生JS - manifest v2 (popup.js) - 方案2
chrome.tabs.executeScript(tabId, {
    code: `var eleID = '${eleID}'; var type = '${type}'; var headerHeight = ${offsetHeight};`
}, function () {
    chrome.tabs.executeScript(tabId, { file: './executeScript.js' });
});
// manifest v2 (executeScript.js)

scrollToTarget(eleID, type, headerHeight);

function scrollToTarget(eleID, type, headerHeight = 40) {
   console.log({eleID, type, headerHeight});
}
问题

但使用Vite打包工具后,在Manifest V2中无法实现相同效果——打包后的文件名是动态生成的,且要执行的函数名会被压缩。以下是我尝试过的两种方案及对应的报错:

方案1

执行后报错:

Could not load file: './executeScript.js'.
注意:打包后的文件名已变为executeScript.1e145e3d.js

browser.tabs.executeScript(tabId, { file: "../executeScript.js" }).then(() => {
    browser.tabs.executeScript(tabId, {
        allFrames: false,
        code: "ht('" + eleID + "', '" + type + "', " + (offsetHeight + 10) + "); ",
    });
});

方案2

执行后报错:

scrollToTarget is not defined
注意:打包后的函数名已改变,例如变为function ht

browser.tabs.executeScript(tabId, {
    allFrames: false,
    code: "scrollToTarget('" + eleID + "', '" + type + "', " + (offsetHeight + 10) + "); ",
});

补充信息

我已使用新的chrome.scripting API在Manifest V3中成功实现该功能,代码如下:

// Manifest v3 可用代码 (popup.js)
chrome.scripting.executeScript({target: {tabId}, files: ['./executeScript.js']}, () => {
  chrome.scripting.executeScript({
    target: {tabId},
    args: [eleID, type, offsetHeight + 10],
    func: (...args) => scrollToTarget(...args),
  });
});
// executeScript.js
function scrollToTarget(eleID, type, headerHeight = 40) {
  console.log({eleID, type, headerHeight});
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:54:33