我想创建一个 Chrome 扩展程序,在其中将星星附加到网页上。我创建了manifest.json、content.js 和style.css 文件。我可以看到图像的位置,但没有显示。我花了 5-6 个小时调试它,但似乎没有任何效果。
这是我的manifest.json:
{
"name": "Random Stars",
"version": "1.0",
"description": "Randomly assigns stars",
"manifest_version": 3,
"content_scripts": [
{
"matches": [
"<all-urls>"
],
"css": [
"style.css"
],
"js": [
"content.js"
]
}
],
"web_accessible_resources": [
{
"resources": [
"star.png"
],
"matches": [ "<all-urls>" ]
}
]
}
内容.js:
if (window.location.hostname === "<url>") {
const companyNames = document.querySelectorAll('<selector>');
companyNames.forEach(companyName => {
const stars = Math.floor(Math.random() * 5) + 1;
const starDiv = document.createElement('div');
starDiv.classList.add('company-stars');
// starDiv.style.backgroundImage = chrome.runtime.getURL("star.png");
starDiv.style.width = `${stars * 20}px`;
companyName.insertAdjacentElement('afterend', starDiv);
});
}
样式.css:
.company-stars {
display: inline-block;
width: 100px;
height: 20px;
background-image: url("star.png");
background-size: contain;
background-repeat: no-repeat;
background-position: center;
margin-left: 5px;
}
我可以看到生成了星星,因为图像的位置在那里并且每个div的长度不同,但图像根本没有显示。
到目前为止我尝试过的:
style.css
转换为content.js
,但没有帮助display
属性,但也没有帮助star.png
与 content.js
、manifest.json
和 style.css
Uncaught DOMException: Failed to read the 'cookie' property from 'Document': The document is sandboxed and lacks the 'allow-same-origin' flag
,但我不认为这是问题所在如果有人有这方面的经验,可以帮我吗?谢谢!
if (window.location.hostname === "<url>") {
const companyNames = document.querySelectorAll('<selector>');
companyNames.forEach(companyName => {
const stars = Math.floor(Math.random() * 5) + 1;
const starDiv = document.createElement('div');
starDiv.classList.add('company-stars');
starDiv.style.backgroundImage = `url(${chrome.runtime.getURL("star.png")})`;
starDiv.style.width = `${stars * 20}px`;
companyName.insertAdjacentElement('afterend', starDiv);
});
}
// in this code u forgot to put url() after backgroundImage, i think this is why it didnt work. here is this corrected code:
starDiv.style.backgroundImage = `url(${chrome.runtime.getURL("star.png")})`;