javascript - 运行使用 chrome.runtime.getURL() 获取的 html 文件的脚本和 css
问题描述
我正在构建一个 chrome 扩展,并希望在激活浏览器操作时将 html 文件的内容添加到文档中。我可以添加 html,但是 css(甚至包含的脚本)没有被激活,尽管我希望它们被激活。
这发生在 content.js(激活的 content_script)中。当按下浏览器操作时,调用此函数:
function addInitialView() {
fetch(chrome.runtime.getURL('searchView.html')).then().then((response) => response.text())
.then((html) => {
$("body").prepend(html)
})
}
searchView.html 的代码是:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
样式是(styles.css)
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
当按钮被激活时,我希望 h1 和 p 出现并在屏幕顶部设置样式。它们都出现了,但它们没有样式(文本仍然是黑色,背景仍然是白色)。
此外,虽然似乎没有应用 css 文件的样式,但具有指向 css 文件的链接确实使文本居中,而不包括它则使其左对齐。我找不到另一个可能添加任何样式的 css 文件。
我已经在清单中添加了和searchView.html
。styles.css
web_accessible_resources
关于如何应用 css,甚至在添加到正文之前运行 html 文件中的脚本的任何建议?
编辑:这是一些额外要求的信息:
清单.json:
{
"manifest_version": 2,
"name": "Extension Name",
"description": "Description",
"version": "0.4.2",
"permissions": ["tabs"],
"icons": {
"16": "active16.png",
"48": "active48.png",
"128": "active128.png"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["./node_modules/jquery/dist/jquery.min.js", "content.js"]
}
],
"browser_action": {
"default_title": "Title"
},
"background": {
"page": "background.html",
"persistent": false
},
"content_security_policy": "script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com https://js.stripe.com/v3/; object-src 'self'",
"web_accessible_resources": [
"searchView.js",
"styles.css",
"searchView.html",
"payment.html",
"active48.png"
]
}
解决方案
您似乎为您的 styles.css 输入了错误的路径。相反,它应该是:
<link rel="stylesheet" type="text/css" href="styles.css">
由于您的位置searchView.html
与styles.css
.
我不使用 jquery,因为它让我们处于基础和依赖状态,但您的脚本在这里:
function addInitialView() {
fetch(chrome.runtime.getURL('searchView.html')).then().then((response) => response.text())
.then((html) => {
$("body").prepend(html)
})
}
它位于正文中,理论上仍然有效,但代码将在单个页面上有多个标题和标题标签。如果必须,请对其进行改进。
您正在使用内容脚本运行 CSS,因此您也可以考虑在 manifest.json 的“content_scripts”部分添加 CSS,如下所示:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["./node_modules/jquery/dist/jquery.min.js", "content.js"],
"css":["style.css"]
}
]
如果您的目标是完全替换页面的全部内容。如果不是,那么您将不得不使用 id 和类使您的风格非常独特。
推荐阅读
- javascript - 如何在 ReactNative React 导航底部选项卡中隐藏一个图标
- c++ - 使用while循环查找数字的平均值
- java - 如何将文本从项目导入 DialogFragment TextView?
- mysql - 带有 INSTR 的 MySQL CASE 语句
- python - np.random.norm 函数取平均值/标准差
- r - 从 dplyr 中的日期范围计算每年的观察值
- angular - 如何在另一个 FormArray 中访问 FormArray
- reactjs - React npm run build 不断失败
- sql - 如何编写排除是否存在查询
- html - 是否有一个 CSS 选择器可以用来在选中复选框后显示元素,无论它在页面上的什么位置?