我正在尝试制作一个弹出窗口,在每个页面上显示时间,但用户可以单击 X 按钮将其关闭。
我不能为此使用 popup.html,因为我正在将其用于其他用途。
基本上,我如何制作这样的东西,显示在每个页面上:
最佳答案
您需要使用内容脚本。内容脚本是可以添加到匹配页面的脚本(以及样式表),您可以定义匹配页面是什么。请参阅https://developer.chrome.com/extensions/content_scripts和 https://developer.chrome.com/extensions/match_patterns可能的匹配模式。
在您的manifest.json中添加以下内容。
"content_scripts": [
{
"matches": ["<all_urls>"],
"css": ["style.css"],
"js": ["script.js"]
}
]
然后,在 script.js 中添加向页面添加弹出窗口的脚本。归功于 bbrame 12 hour AM/PM code .
var div = document.createElement("div");
div.setAttribute("id", "chromeextensionpopup");
div.innerText = formatAMPM(new Date());
document.body.appendChild(div);
var closelink = document.createElement("div");
closelink.setAttribute("id", "chromeextensionpopupcloselink");
closelink.innerText = 'X';
document.getElementById("chromeextensionpopup").appendChild(closelink);
function formatAMPM(date){
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
document.getElementById("chromeextensionpopupcloselink").addEventListener("click", removeExtensionPopup);
function removeExtensionPopup(){
document.getElementById("chromeextensionpopup").outerHTML='';
}
在 style.css 中,您可以将 CSS 设置为样式,将其放在 Angular 落或任何您想要的位置等。
#chromeextensionpopup{
background: white;
border: solid 3px black;
line-height: 25px;
position: absolute;
right: 20px;
text-align: center;
top: 20px;
width: 100px;
z-index: 999999999;
}
#chromeextensionpopupcloselink{
background: red;
color: white;
cursor: pointer;
float: right;
height: 25px;
text-align: center;
width: 25px;
}
关于javascript - 如何向我的 Chrome 扩展程序添加弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27760346/