我想创建一个 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??????
});
最佳答案
您需要为弹出窗口以及按钮注入(inject)所有 DOM。
您可以在按钮的点击事件中执行此操作:
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>
关于javascript - Chrome 扩展按钮弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43563816/