Chrome扩展程序按钮弹出窗口

4
我想创建一个chrome扩展程序,在特定页面上添加一个按钮,单击该按钮时,我希望弹出显示在https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_popup中的弹出窗口。
我已经使用了内容脚本,并将那个链接中的CSS内容包含在.css文件中,另外我还有一个为内容脚本的.js文件,它会向屏幕注入一个按钮。
我的按钮已经出现在屏幕上。我想知道的是,我该如何使像链接中所示的弹出窗口出现?他们在链接中使用了一个HTML文件,但我通过内容脚本对已经存在的HTML页面进行更改。那么我该怎么做呢?
我的内容脚本.js文件:
var button = document.createElement("button");
//button description

var body = document.getElementsByClassName("htmlclassname")[0];
body.insertBefore(button, body.childNodes[0]);
//Button appearing properly

button.addEventListener("click", function() {
    //What code do I put here to get a popup like in the link??????
});
2个回答

2

您需要将弹出窗口的所有DOM以及按钮注入。

您可以在按钮的“click”事件中执行此操作:

var button = document.createElement('button');
button.innerText = 'Show Popup';
button.style.position = 'relative';

document.querySelector('body').appendChild(button);

button.addEventListener('click', function(e) {
  var popup = document.querySelector('#myPopup');
  if (!popup) {
    popup = document.createElement('div');
    popup.style.visibility = 'hidden';
    popup.style.width = '160px';
    popup.style.backgroundColor = '#555';
    popup.style.color = '#fff';
    popup.style.textAlign = 'center';
    popup.style.borderRadius = ' 6px';
    popup.style.padding = '8px 0';
    popup.style.position = 'absolute';
    popup.style.zIndex = '1';
    popup.style.bottom = '125%';
    popup.style.left = '50%';
    popup.style.marginLeft = '-80px';
    popup.innerText = 'A Simple Popup!';
    popup.id = 'myPopup';
    button.appendChild(popup);
  }

  if (popup.style.visibility === 'hidden')
    popup.style.visibility = 'visible';
  else
    popup.style.visibility = 'hidden';
});
<div>Content already in page.
  <p>blah blah blah</p>
</div>


谢谢Keith。这样可以完成工作,但在提问后进行了大量研究(我对所有这些都很新),我发现更好的解决方案是创建一个div,如var div = document.createElement("div"),并将按钮、弹出窗口以及我想要的所有内容添加到html中,如div.innerHTML = " . . . "。这样我也可以轻松使用css类和选择器! - Saurabh Shirodkar
1
@SaurabhShirodkar 你可以这样做。但要小心,因为页面的内容安全策略可能会阻止内联CSS。 - Keith
@Keith,这个工作得非常好。我卡了一段时间了,谢谢! - swagless_monk

0

您可能想要查看入门指南:构建Chrome扩展程序,其中展示了如何在单击图标后实现打开弹出窗口的功能。如给定链接中所述,弹出窗口内容的实际渲染逻辑由popup.js实现。

然后,在您的第一个扩展程序运行起来之后,您可以调整代码以完全按照您的意愿进行设置,例如在浏览器操作按钮上设置工具提示。

可以通过在清单文件中指定default_title键来设置工具提示。打开manifest.json,并将default_title键添加到browser_action中。确保JSON有效,因此引用键并在必要时添加逗号。

示例代码:

{
  ...
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Click here!"
  },
  ...
}

这个相关的SO post中提出的解决方案可能也有帮助。


这不是我要找的东西。我不是指Chrome浏览器栏中的图标,而是在页面加载后通过内容脚本注入到HTML中的实际按钮。 - Saurabh Shirodkar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接