如何在chrome扩展中更新onBeforeRequest事件监听器?

时间:2014-10-02 08:29:22

标签: javascript google-chrome-extension

我在后台页面中有一个带有以下事件监听器的扩展程序...

chrome.webRequest.onBeforeRequest.addListener(
    function(details){
        if ( ... details.url is in ArrayOfURLs ...  ){
            ... do stuff ...
        }
    }, {
        urls:  ["<all_urls>"],
        types: ["main_frame"]
    }, ["blocking"]
);

我想要做的是首先将url数组传递给事件监听器。所以看起来应该是这样......

chrome.webRequest.onBeforeRequest.addListener(
    function(details){
        ... do stuff ...
    }, {
        urls:  ArrayOfURLs,
        types: ["main_frame"]
    }, ["blocking"]
);

当我从ArrayOfURLs数组添加/删除项目时,有没有办法可以更新事件监听器?

1 个答案:

答案 0 :(得分:1)

通常的做法是删除旧处理程序并添加一个新处理程序。

function requestHandler(details){
  /* ... do stuff ... */
}

function setListener(ArrayOfURLs) {
  chrome.webRequest.onBeforeRequest.removeListener(requestHandler);
  chrome.webRequest.onBeforeRequest.addListener(
    requestHandler,
    { urls: ArrayOfURLs, types: ["main_frame"] },
    ["blocking"]
  );
  chrome.webRequest.handlerBehaviorChanged();
}

需要最后一次通话,因为Chrome会缓存规则,但它是very expensive in terms of performance