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

如何在Chrome扩展内容脚本中使用Floating UI并解决ESM导入错误?

解决Chrome扩展内容脚本中使用Floating UI ESM的语法错误

错误原因

你遇到的Uncaught SyntaxError: Cannot use import statement outside a module错误,本质是两个问题:

  • 内容脚本中引入的floating-esm.js包含指向外部CDN的import语句,Chrome扩展的隔离环境及CSP限制会阻止跨源加载ESM模块;
  • 即使manifest设置了type: module,非本地合法ESM模块的导入方式也会触发语法错误。

解决方案

方案一:使用本地ESM模块(推荐)

  1. 安装Floating UI核心包
npm install @floating-ui/core
  1. 从node_modules/@floating-ui/core/dist/目录下复制index.esm.js到你的扩展目录,重命名为floating-ui.esm.js
  2. 修改content.js,导入本地模块:
import { computePosition, rectToClientRect } from './floating-ui.esm.js';

// 示例tooltip逻辑
function showTooltip(element, content) {
  const tooltip = document.createElement('div');
  tooltip.className = 'custom-tooltip';
  tooltip.textContent = content;
  document.body.appendChild(tooltip);

  computePosition(element, tooltip, {
    placement: 'top'
  }).then(({ x, y }) => {
    Object.assign(tooltip.style, {
      left: `${x}px`,
      top: `${y}px`
    });
  });
}
  1. 更新manifest配置(无需单独引入Floating UI文件,由content.js导入即可):
"content_scripts": [
  {
    "matches": ["*://*/*"],
    "js": ["content.js"],
    "type": "module",
    "css": ["tooltips.css"]
  }
]

方案二:使用UMD版本规避模块问题

如果不想使用ESM,可改用Floating UI的UMD全局版本:

  1. 下载@floating-ui/core/dist/index.umd.js到扩展目录,命名为floating-ui.umd.js
  2. 修改manifest配置(移除type: module):
"content_scripts": [
  {
    "matches": ["*://*/*"],
    "js": ["floating-ui.umd.js", "content.js"],
    "css": ["tooltips.css"]
  }
]
  1. 在content.js中通过全局变量访问函数:
const { computePosition, rectToClientRect } = FloatingUI.core;

// 编写tooltip逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:17:13