简体   繁体   中英

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

I'm trying to make a popup window that shows the time on every page, but the user can click the X button to close it.

I can't use popup.html for this because I'm using that for something else.

Basically how do I make something like this that shows on every page:

在此处输入图片说明

You need to use a Content Script. Content Scripts are scripts (and also stylesheets) that can be added to matching pages, and you can define what a matching page is. See https://developer.chrome.com/extensions/content_scripts and https://developer.chrome.com/extensions/match_patterns for possible match patterns.

In your manifest.json add the below.

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

Then, in your script.js add the script that adds a popup to the page. Credit to bbrame for 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='';
}

And in style.css you can put your CSS to style it, put it in the corner or whatever you want etc.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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