0

setTimeout我正在为一个简单的 Chrome 扩展程序编写代码,但是在清除正确的实例和更新正确的 Chrome 选项卡时遇到问题。我想为对 URL 的请求设置计时器,如果收到响应,则应清除相应的实例。如果响应超时,定时器功能应该更新相应的窗口dialog.html。问题是,响应会清除最后一个计时器,并且计时器函数会更新当前选项卡。我试过了,window.setTimeoutrequest.tabId作为参数传递给定时器函数,但两者都不起作用。谢谢你的帮助,

背景.js

var flag = false;
var new_url;
var timeout;

function resp_timeout(){
  var dialog_url = chrome.extension.getURL("dialog.html"); 
  chrome.tabs.update({url: dialog_url});
}


chrome.webRequest.onBeforeRequest.addListener(
  function interceptRequest(request) {
    if (isOn) {     
       original_url = request.url;                      
       if (request && request.url) {        
        if(flag){
        new_url = request.url; 
        }
       else { 
        new_url = request.url.replace("http","https");
        timeout = setTimeout(resp_timeout, 500);  
       }
        return { redirectUrl: new_url }
      }   
   }   
}, {urls: ['http://*/*']}, ['blocking']); 

chrome.webRequest.onHeadersReceived.addListener(function(details) {
  if (isOn) {    
    clearTimeout(timeout);    
    return {responseHeaders:headers};
  }
}, {urls: ['*://*/*']}, ['responseHeaders','blocking']); 

对话框.js:

var bg = chrome.extension.getBackgroundPage();

function ok_handler(){  
 window.open(bg.original_url, "_self");
}

function cancel_handler(){
  window.close();
}

document.addEventListener('DOMContentLoaded', function () {
  document.querySelector('#ok_button').addEventListener('click', ok_handler);
  document.querySelector('#cancel_button').addEventListener('click', cancel_handler);
});
4

1 回答 1

1

您将必须存储多个超时,每个活动请求一个。您可以通过 来识别它们requestId。此外,您需要生成不同的回调函数,每个回调函数来更新正确的选项卡:

var timeouts = {};

function get_resp_timeout(tabId, requestId) {
   return function() {
      var dialog_url = chrome.extension.getURL("dialog.html"); 
      chrome.tabs.update(tabId, {url: dialog_url});
      delete timeouts[requestId];
   }
}
...
        timeouts[request.requestId] = setTimeout(
           get_resp_timeout(request.tabId, request.requestId), 500);
...
    clearTimeout(timeouts[details.requestId]);
    delete timeouts[details.requestId];
于 2013-07-16T18:14:27.573 回答