繁体   English   中英

如何在Chrome扩展程序中添加弹出窗口?

[英]How do I add a popup window to my Chrome Extension?

我正在尝试创建一个弹出窗口,以在每个页面上显示时间,但是用户可以单击X按钮将其关闭。

我不能为此使用popup.html,因为我正在将其用于其他用途。

基本上,我如何做这样的事情显示在每个页面上:

在此处输入图片说明

您需要使用内容脚本。 内容脚本是可以添加到匹配页面的脚本(以及样式表),您可以定义什么是匹配页面。 有关可能的匹配模式,请参见https://developer.chrome.com/extensions/content_scriptshttps://developer.chrome.com/extensions/match_patterns

在您的manifest.json中添加以下内容。

"content_scripts": [
   {
      "matches": ["<all_urls>"],
      "css": ["style.css"],
      "js": ["script.js"]
   }
]

然后,在您的script.js中添加向页面添加弹出窗口的脚本。 归功于bbrame 12小时AM / PM代码

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样式化,放在角落或任何您想要的样式中。

#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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM