gpt4 book ai didi

javascript - 在 Chrome 扩展程序中在后台执行多个 ajax 请求

转载 作者:行者123 更新时间:2023-12-03 06:02:17 27 4
gpt4 key购买 nike

我遇到一种情况,我需要通过 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 的实现、错误处理和弹出窗口留给读者作为练习。

关于javascript - 在 Chrome 扩展程序中在后台执行多个 ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39707043/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com