我的Chrome扩展的弹出窗口打开一个新窗口通过窗口打开(),当我点击按钮(登录)存在于弹出屏幕的身份验证,身份验证完成后,子窗口关闭,但它关闭了扩展的弹出本身。在用户注意到验证完成后的消息之前,扩展弹出会很快消失。
窗口是这样打开的
window.open(url, target, windowFeatures)
这是因为焦点在窗口之间移动吗?我该怎么做才能让弹出窗口保持更长时间,以便用户注意到消息?
创建一个新的选项卡与弹出,它将创建一个窗口的身份验证
popup.html
<html>
<body>
<script src="popup.js"></script>
</body>
</html>
popup.js
chrome.tabs.create({ url: "auth.html" });
auth.html
<html>
<body>
<button id="auth">auth</button>
<script src="auth.js"></script>
</body>
</html>
auth.js
document.getElementById("auth").onclick = () => {
auth();
}
当您在弹出窗口中运行此代码时,它会在后台打开一个新选项卡并保持弹出窗口打开:
chrome.tabs.create({ active: false, url: "https://stackoverflow.com/" });
当你在弹出窗口中调用chrome.tabs.remove关闭新选项卡时,弹出窗口仍然保持打开状态
还有chrome.windows。创建,但它总是关闭弹出窗口,即使你调用它与focused: false
和/或state: "minimized"
在Chromium 108.0.5359.124(官方版本)Arch Linux(64位)中测试
概念证明:
manifest.json
{
"manifest_version": 3,
"name": "Open new Tab from Popup",
"version": "1.0.0",
"action": {
"default_popup": "popup.html"
}
}
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Open new Tab from Popup</title>
</head>
<body>
<h1>Open new Tab from Popup</h1>
<button id="create_tab">Create Tab</button>
<button id="close_tab">Close Tab</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
let tab_id = null;
async function create_tab(event) {
if (tab_id === null) {
let tab = await chrome.tabs.create({ active: false, url: "https://stackoverflow.com/" });
tab_id = tab.id;
}
else {
console.log("There is already an open tab.");
}
}
function close_tab(event) {
if (tab_id === null) {
console.log("There is no open tab.");
}
else {
chrome.tabs.remove(tab_id);
tab_id = null;
}
}
document.getElementById("create_tab").addEventListener("click", create_tab);
document.getElementById("close_tab").addEventListener("click", close_tab);
注意:
当你关闭弹出窗口,扩展忘记新选项卡的ID。
因此,以下事件序列创建了一个需要手动关闭的选项卡:
- 打开弹出窗口
- 点击"创建选项卡"按钮
- 关闭弹出
- 再次打开弹出窗口
- 点击"关闭"选项卡;按钮