【发布时间】:2020-05-19 05:05:38
【问题描述】:
我正在构建一个 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 文件中的脚本有什么建议吗?
编辑: 以下是一些额外要求的信息:
manifest.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"
]
}
【问题讨论】:
-
您是否尝试过将它们直接写入 HTML 文档而不是调用样式作为实例?
<style>body { background-color: powderblue; } h1 { color: blue; } p { color: red; }</style> -
或者您可以像现在获取 html 一样显式获取这些 css 文件(并添加 DOM 样式元素),或者在 html 中使用完全限定的 URL,例如 chrome-extension://__MSG_@@extension_id__/foo。 CSS
-
@raku 这确实有效,但我认为它不会成为一个非常可扩展的解决方案。但这确实让我觉得文件/源可能有问题,所以我添加了一个测试脚本,它只是做了一个日志,地址是
searchView.js。虽然失败了,但没有找到——需要使用 chrome.runtime.findURL 之类的东西。为此,您能否解释一下如何使用完全限定的 url @wOxxOm?我尝试了您的示例(替换 foo),但得到了chrome-extension://invalid/ -
这里可能会发生两件事。我可以看看你的 manifest.json 和你的扩展文件夹位置的截图吗?
-
嗯,这个完整的 URL 技巧只适用于 css 文件,而不适用于 html。您可以在
html参数上使用 replace() 将此完整 URL 插入到 html 字符串中,或者在插入后使用 jquery 方法添加指向 css 文件的样式元素。
标签: javascript html jquery css google-chrome-extension