我对Chrome扩展程序的编码是完全陌生的,并且我对JS不太熟悉,但是我希望有人可以提供帮助。我正在尝试创建一个扩展名,该扩展名会在用户点击时触发弹出式窗口,以显示不同的文本块,具体取决于用户所在的网页,大多数页面使用默认文本块,但某些网站显示自定义文本块。
我已经能够使弹出窗口正常工作,但是我在检查URL是否包含要比较的url片段所需的结构和编码方面遇到了麻烦。我试图使用单个popup.html文件,并使用Divs和CSS仅显示希望弹出窗口显示的特定文本,而不是尝试引用多个popup.html类型文件。我已经阅读了很多文章,但是找不到适合我要用作学习参考的东西。我从一个CSS开始,该CSS最初将显示设置为“无”,目的是仅公开相关的给定文本。
这是我第一次尝试使用Chrome扩展程序,尽管进行了大量的搜索和阅读,但我似乎无法将其组合在一起。我怀疑我的问题的一部分是我的进程不正常,我试图在将所有文本设置为不显示之前公开给定的文本块,而应该在我引用的popup.js文件中采取措施来自popup.html,但我似乎无法弄清楚如何正确了解和比较网址。目前,当我单击按钮时,会出现弹出窗口,其格式设置为正确的宽度,但是内容始终为空白。这是我到目前为止的内容:
manifest.json
{
"manifest_version": 2,"version": "1.0","name": "Varibale Popup Test","description": "Variable message popup","permissions": [
"tabs","<all_urls>"
],"background": {
"scripts": ["background.js"]
},"browser_action":
{
"default_icon": "images/get_started128.png","default_popup": "popup.html"
},"icons": {
"16": "images/get_started16.png","32": "images/get_started32.png","48": "images/get_started48.png","128": "images/get_started128.png"
}
}
background.js
chrome.tabs.onUpdated.addListener( function( tabId,changeInfo,tab) {
chrome.extension.getBackgroundPage().console.log(tab.url);
if (tab.url.indexOf ("url1.com") > -1) { {
document.getElementById('#Test1').style.display = block;
}
else if (tab.url.indexOf('url2') > -1) { {
document.getElementById('#Test2').style.display = block;
}
else
{
document.getElementById('#Test3').style.display = block;
}
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Verbal TPA under $5000 </title>
<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
<div id="Test1" class="dynamic-content">
Test1 Text
</div>
<div id="Test2" class="dynamic-content">
Test2 Text
</div>
<div id="Test3" class="dynamic-content">
Test3 Text
</div>
</body>
</html>
popup.css
body {
min-width: 780px;
max-height: 300px;
font-size: 20px;
}
.dynamic-content {
display:none;
}
更新: wOxxOm最初提出的代码可以完美地工作,但是除了提供的说明之外,我还必须重命名Div ID以从Test0代替Test1。否则下面的popup.js可以完美地工作:
const testUrls = [
'url1.com','url2.com',];
chrome.tabs.query({active: true,currentWindow: true},([tab]) => {
const i = testUrls.findIndex(u => tab.url.includes(u));
document.getElementById(`Test${i < 0 ? 3 : i}`).style.display = 'block';
});