尽管在控制台中可用

发布于 2025-01-19 00:48:17 字数 1826 浏览 4 评论 0原文

我正在尝试使用 day.js 我的扩展名中的库。数据将使用browser.runtime.sendmessage()从我的内容脚本传递到我的背景脚本,这是我使用day.js的地方。

奇怪的是,错误:Dayjs不是一个函数出现在网页的控制台中,内容脚本运行(例如工具箱?id = my-extension& type = Extension )。我正在使用Firefox。

此外,我可以运行dayjs()的控制台上没有问题:DevTools-Toolbox。为什么它在我的背景脚本中不起作用?为什么错误出现在内容脚本的上下文中?

background.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <!-- Background page is necessary for supporting ES6 modules -->
    <script type="module" src="background.js"></script>
  </head>
</html>

background.js

import * as dayjs from "./[email protected]/dayjs.min.js";
import * as relativeTime from "./[email protected]/relativeTime.js";

async function calculateAge(datetimeString) {
  const datetime = dayjs(datetimeString);

  dayjs.extend(relativeTime);

  const age = datetimeCreated.fromNow();
  return age;
}

browser.runtime.onMessage.addListener(calculateAge);

content.js

async function getAge(datetimeString) {
  const age = await browser.runtime.sendMessage(datetimeString);
  return age;
}

subtest.json.json

"background": {
  "page": "background.html"
},

"content_scripts": [
  {
    "js": ["content.js"],
    "matches": ["https://*.google.com/*"]
  }
],

I'm trying to use the day.js library in my extension. Data is passed using browser.runtime.sendMessage() from my content script to my background script, which is where I use day.js.

Oddly enough, Error: dayjs is not a function appears in the console of the webpage where the content script runs (e.g. google.com rather than about:devtools-toolbox?id=my-extension&type=extension). I'm using Firefox.

Furthermore, I can run dayjs() with no problems in the console of about:devtools-toolbox. Why doesn't it work in my background script? And why does the error appear in the content script's context?

background.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <!-- Background page is necessary for supporting ES6 modules -->
    <script type="module" src="background.js"></script>
  </head>
</html>

background.js:

import * as dayjs from "./[email protected]/dayjs.min.js";
import * as relativeTime from "./[email protected]/relativeTime.js";

async function calculateAge(datetimeString) {
  const datetime = dayjs(datetimeString);

  dayjs.extend(relativeTime);

  const age = datetimeCreated.fromNow();
  return age;
}

browser.runtime.onMessage.addListener(calculateAge);

content.js:

async function getAge(datetimeString) {
  const age = await browser.runtime.sendMessage(datetimeString);
  return age;
}

manifest.json:

"background": {
  "page": "background.html"
},

"content_scripts": [
  {
    "js": ["content.js"],
    "matches": ["https://*.google.com/*"]
  }
],

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文