【问题标题】:How do I add a popup window to my Chrome Extension?如何将弹出窗口添加到我的 Chrome 扩展程序?
【发布时间】:2015-01-03 22:44:42
【问题描述】:

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

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

基本上我如何制作这样的东西,显示在每个页面上:

【问题讨论】:

  • 你试过什么? [Related]
  • 我尝试使用 background.js 但我不知道要添加什么代码。
  • 我附加的链接是使用内容脚本而不是后台脚本。你可能想look into that。

标签: javascript google-chrome-extension


【解决方案1】:

您需要使用内容脚本。内容脚本是可以添加到匹配页面的脚本(以及样式表),您可以定义匹配页面是什么。请参阅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 中添加向页面添加弹出窗口的脚本。感谢 12 hour AM/PM code 的 bbrame。

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

【讨论】:

  • 谢谢 我刚刚添加了所有代码,但没有显示弹出窗口?我不知道如何设置样式或创建弹出窗口,所以我错过了什么?
  • 我已经更新了我的答案,以便为你包括这个。我在这里创建了一个示例扩展 www46.zippyshare.com/v/69100728/file.html
  • 哇,谢谢老兄!我刚刚添加了该代码并且它有效!我需要的另一件事是能够通过单击扩展图标来隐藏和显示时间。有没有办法做到这一点?
  • 对不起,我的意思是有办法隐藏和显示日期,直到点击扩展图标。因此,如果我单击扩展图标一次,则在我再次单击该图标之前,时间不会出现在任何页面上。
猜你喜欢
  • 2012-02-17
  • 2012-05-07
  • 2023-01-02
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2011-09-27
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多