执行多个ajax请求在后台Chrome扩展
Perform multiple ajax requests in background in Chrome extension
我有一个情况,我需要通过chrome扩展击中多个ajax请求,并显示成功的结果在chrome扩展的弹出式html。
我将循环数组中的url列表并在ajax请求中执行。这工作得很好,直到我的chrome扩展打开。但只要我点击外部或更改选项卡,扩展被关闭,脚本被终止。
我有一个按钮在我的扩展。当我点击它时,我需要在后台击中所有的ajax,当我打开扩展(无论多少次),它必须显示有多少请求完成(基本上是ajax的成功结果)。
有谁能帮我一下吗
根据设计,每次失去焦点时弹出窗口都会被销毁(而不是隐藏),这会导致脚本终止。
另一方面,后台页面(在某种程度上,事件页面)被设计为"永远在那里",并进行冗长的处理或永远在线的事件处理。
所以,你需要两个:一个后台页面进行处理和弹出窗口显示UI。
思路如下:
- 后台页面有一个消息监听器,可以:
- 启动AJAX处理
- 根据请求返回当前进度
- 每当进度发生变化时,后台页面都会发出一条消息
- 当弹出页面打开时,从后台请求当前进度
- 之后,只要它被打开,它就会从后台监听进度消息。
像这样:
+--------------+ message: request +--------------+ time
| Background | progress | Popup | |
| page | <------------------- | window | '|/
| | respond: stopped | |
| | -------------------> | ( display ) |
| | | ( start ) |
| | | ( button ) |
| | | |
| | message: | |
| | start AJAX | ( user ) |
| ( starts ) | <------------------- | ( clicks ) |
| ( AJAX ) | | |
| | | |
... ...
| | | |
| ( some ) | message: | |
| ( AJAX ) | progress N/M | ( update ) |
| ( done ) | -------------------> | ( progress ) |
| | | ( N/M ) |
| | +--------------+
| | ( popup )
| ( some ) | message: ( closes )
| ( AJAX ) | progress N+1/M
| ( done ) | ------ ??? (nothing listens)
| |
| | message: request +--------------+
| Background | progress | Popup |
| page | <------------------- | window |
| | respond: N+1/M | |
| | -------------------> | ( display ) |
| | | ( progress) |
| | | ( N+1/M ) |
| ( some ) | message: | |
| ( AJAX ) | progress N+2/M | ( update ) |
| ( done ) | -------------------> | ( progress ) |
| | | ( N+2/M ) |
... ...
背景页面的示例实现:
var done = 0;
var total = 0;
var processing = false;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
switch (message.type) {
case "queryProgress":
sendResponse({
processing: processing,
total: total,
done: done
});
break;
case "startProcessing": // Assumes the list of AJAX to process
doAllAJAX(message.list); // is passed in the message
break;
}
});
function doAllAJAX(list) {
total = list.length;
done = 0;
processing = true;
/* Initiate AJAX processing here for the list with onAJAXSuccess as a callback */
}
function onAJAXSuccess() {
done++;
if (done == total) { processing = false; }
chrome.runtime.sendMessage({
type: "progressReport",
processing: processing,
total: total,
done: done
});
}
AJAX的实现,错误处理和弹出窗口的左侧,作为读者的练习。
相关文章:
- 在chrome web商店中打开时,是否有允许执行内容/后台脚本的解决方案
- 通过chrome后台扩展或后台应用程序访问用户麦克风
- Chrome 扩展程序在后台与页面(不在标签页中)交互
- JavaScript 在后台打开窗口,而不是在 Chrome 和 Safari 中打开前台
- Chrome 打包应用程序 - 在后台/事件页面中使用 AngularJS
- Chrome 扩展程序在后台注册事件.js
- 后台的Chrome扩展程序键关闭侦听器.js
- 在chrome扩展中获取从后台页面到内容脚本的配置
- 弹出的Chrome扩展后台页面
- 使用chrome扩展,如何使用长寿命连接(端口)将消息从后台脚本传递到内容脚本
- 如何在chrome扩展中检索活动选项卡、后台消息侦听器内部
- Chrome扩展:通过服务器上的JavaScript将请求发送到后台页面
- Chrome扩展使用后台页面+内容脚本
- chrome延长时间,后台任务
- 如何让chrome扩展在页面加载的后台执行功能
- Chrome扩展:在后台页面和网站页面脚本之间进行通信的最佳方法
- 后台位置的计算样式在Chrome中返回0%0%
- 为什么chrome.sockets.tcp.create()在应用程序后台脚本中不起作用
- 使用chrome扩展程序在后台自动进行条件浏览
- 执行多个ajax请求在后台Chrome扩展