阻止 Chrome 扩展程序的 popup.html 自行打开
我正在创建一个 Chrome 扩展程序,它有一个 background.html
文件,该文件每分钟从 API 请求一次信息。收到信息后,它会向 popup.html
发送包含 JSON 信息的消息,弹出窗口使用该信息将新的 HTML 元素附加到弹出窗口的主体上。
问题是后台不断运行(理应如此),但即使弹出窗口关闭,它也会对弹出窗口执行 ping 操作。这会导致弹出窗口每分钟都会打开,这非常烦人。
我想知道,有没有办法查看弹出窗口是否关闭并且如果是这种情况则不执行任何操作?或者有其他方法可以防止弹出窗口自行打开吗?
这是 Github 存储库,但重要部分在下面突出显示。
以下是我 ping 弹出窗口的方式:
// background.js
function sendQuestions()
{
var questions = JSON.parse(db.getItem(storage));
chrome.extension.sendRequest(appid, { 'questions': questions }, function() {});
}
setInterval(sendQuestions, 60e3);
以下是弹出窗口处理它的方式:
// popup.js
chrome.extension.onRequest.addListener(function(request) {
if (request.questions) {
displayQuestions(request.questions);
}
});
function displayQuestions(questions)
{
for (i = 0; i < questions.length; i++) {
var question = questions[i];
var htmlBlock = // ... generate a block of html ...
$('#container').prepend(htmlBlock);
}
}
I'm creating a Chrome extension that has a background.html
file which requests information from an API once every minute. Once it receives the information, it messages popup.html
with the JSON information with which popup uses to append new HTML elements onto the popup's body.
The problem is background is constantly running (as it should), but it will ping popup even when popup is closed. This causes popup to open itself every minute which is very annoying.
I want to know, is there a way to see if popup is closed and not do anything if that's the case? Or is there another way to prevent popup opening on its own?
Here's the Github repository, but the important parts are highlighted below.
Here's how I'm pinging popup:
// background.js
function sendQuestions()
{
var questions = JSON.parse(db.getItem(storage));
chrome.extension.sendRequest(appid, { 'questions': questions }, function() {});
}
setInterval(sendQuestions, 60e3);
Here's how popup handles it:
// popup.js
chrome.extension.onRequest.addListener(function(request) {
if (request.questions) {
displayQuestions(request.questions);
}
});
function displayQuestions(questions)
{
for (i = 0; i < questions.length; i++) {
var question = questions[i];
var htmlBlock = // ... generate a block of html ...
$('#container').prepend(htmlBlock);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
随时打开从弹出窗口到后台页面的长实时连接打开。在后台页面中,您可以检查连接当前是否处于活动状态。如果是,则传递必要的消息,否则请等待,直到连接处于活动状态。
Open a long lived connection from the popup to the background_page anytime it opens. In the background_page you can check to see if the connection is currently active. If it is pass the necessary messages otherwise wait until the connection is active.