2016-09-26 83 views
0

我有一种情况,我需要通过Chrome扩展打多个Ajax请求,并在Chrome扩展的弹出式HTML中显示成功。在Chrome扩展中在后台执行多个Ajax请求

我将在数组中循环url列表并在ajax请求中执行。这很好,直到我的Chrome扩展打开。但只要我点击外部或更改选项卡,扩展程序就会关闭并且脚本被终止。

我在我的扩展中有一个按钮。当我点击它时,我需要在后台打开所有ajax,当我打开扩展(无论多少次)时,它必须显示完成了多少请求(基本上是ajax的成功结果)。

有人可以帮我解决它。

+4

它在[扩展概述:体系结构](https://developer.chrome.com/extensions/overview#arch)中有描述:使用背景/事件页面和[消息](https://developer.chrome.com /扩展/消息)。如果你幸运的话,会有人提供一个详细的例子。 – wOxxOm

+0

@ wOxxOm他今天很幸运。 – Xan

回答

1

弹出式窗口在设计上会在每次失去焦点时被销毁(而不是隐藏),这会导致脚本终止。另一方面,背景页面(以及某种程度上的事件页面)被设计为“永远在那里”,并进行冗长的处理或始终在线的事件处理。

所以,你需要两个:一个后台页面来做处理和弹出来显示用户界面。

的想法如下:

  • 背景页面有一个消息监听器能够:
    • 启动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,错误处理实施和作为练习留给读者弹出。

相关问题