彈出式窗口在設計上會在每次失去焦點時被銷燬(而不是隱藏),這會導致腳本終止。另一方面,背景頁面(以及某種程度上的事件頁面)被設計爲「永遠在那裏」,並進行冗長的處理或始終在線的事件處理。
所以,你需要兩個:一個後臺頁面來做處理和彈出來顯示用戶界面。
的想法如下:
- 背景頁面有一個消息監聽器能夠:
- 的每當進度發生變化時,後臺頁面會發出一條消息
- 彈出頁面打開時請求當前背景進度
- 之後,只要它打開,它就會偵聽來自後臺的進度消息。
事情是這樣的:
+--------------+ 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,錯誤處理實施和作爲練習留給讀者彈出。
來源
2016-09-26 21:16:32
Xan
它在[擴展概述:體系結構](https://developer.chrome.com/extensions/overview#arch)中有描述:使用背景/事件頁面和[消息](https://developer.chrome.com /擴展/消息)。如果你幸運的話,會有人提供一個詳細的例子。 – wOxxOm
@ wOxxOm他今天很幸運。 – Xan