【问题标题】:Non blocking alert for a chrome extension popup windowchrome 扩展弹出窗口的非阻塞警报
【发布时间】:2015-10-08 06:05:30
【问题描述】:
我正在制作一个 chrome 扩展,为此我需要在弹出窗口中添加一些非阻塞警报。定期警报会暂停 javascript 代码执行,而客户端不希望这样。我尝试使用 jQuery 的 UI 对话框,但是当我单击“确定”按钮关闭它时,弹出窗口失去焦点并关闭。关于如何向弹出窗口添加持久性或如何从弹出窗口创建非阻塞警报的任何建议?
更新:问题在于 content.js 是创建警报的那个。所以当我点击它时,弹出窗口失去焦点并关闭。有什么方法可以创建附加到 popup.html 而不是当前选项卡中加载的页面的警报?
【问题讨论】:
标签:
javascript
jquery
google-chrome-extension
【解决方案1】:
只需在弹出窗口中显示对话框,因为它只能在其严格限制的范围(最大 750 像素或 800 像素)内显示内容,并且您不能从外部“附加”某些内容。
-
从您的内容脚本发送消息并等待侦听器中的响应:
if (someCondition) {
chrome.runtime.sendMessage({action: "alert", text: "STOP!"});
}
chrome.runtime.onMessage.addListener(function(msg) {
if (msg.action == "alert-response") {
doSomething(msg.response);
}
});
-
所有打开的弹出窗口都会收到消息,活动的弹出窗口会显示一个警报 UI,当单击其任何按钮时,会向内容脚本发送一条响应消息,其中包含按钮的 id:
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == "alert") {
// if several popups are visible in different windows only one should respond
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
if (tabs[0].id == sender.tab.id) {
showAlert(msg.text);
}
});
}
});
function showAlert(text) {
// show the nonblocking dialog
................................
btnOK.addEventListener("click", buttonClick);
btnCancel.addEventListener("click", buttonClick);
function buttonClick(event) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {
action: "alert-response",
response: event.target.id // id of the clicked button: "ok", "cancel"
}
});
}
}