尽管在控制台中可用
我正在尝试使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论