chrome.pageAction.show 仅适用于超时

chrome.pageAction.show only works with timeout

我正在编写一个 chrome 扩展程序,它应该在加载 PDF 时显示页面操作图标。为此,我正在检查内容类型,如果它等于 application/pdf,我 chrome.pageAction.show(tabId)。然而,令我惊讶的是,这

chrome.webRequest.onHeadersReceived.addListener(
  function(details) { 
    if (details.tabId >= 0) { 
      var header = getContentTypeFromHeaders(
        details.responseHeaders,
        'content-type'
      );
      global.tabToMimeType[details.tabId] = 
        header && header.value.split(';', 1)[0];
      if (global.tabToMimeType[details.tabId] === 'application/pdf') { 
        chrome.pageAction.show(details.tabId);
      }
    }
  },
  { 
    urls: ['*://*/*.pdf'],
    types: ['main_frame']
  },
  ['responseHeaders']
);

不起作用。我有时可以看到图标闪烁,但它永远不会持续存在。相反,如果我替换

chrome.pageAction.show(details.tabId);

来自

setTimeout(function() {
    chrome.pageAction.show(details.tabId);
}, 100);

一切都很好。对此有何解释?还有比等待100毫秒更系统的方法吗?

我认为问题在于您尝试显示得太早,在导航由选项卡处理之前。

所以你的图标出现了,然后页面转换并且图标被擦除。

尝试将您的逻辑移动到 onResponseStarted 甚至 onCompleted

因为这还不够,而且很难将 webRequest 事件与 tabs/webNavigation 事件联系起来,您可以继续您的方法或尝试找到使用 tabs/webNavigation API.

检测 PDF 的另一种方法

webNavigation 文档中的这句话说明了我的意思:

In general, the webNavigation events are closely related to the navigation state that is displayed in the UI, while the webRequest events correspond to the state of the network stack which is generally opaque to the user.

因此 webRequest 事件与选项卡转换无关,不能可靠地用于显示页面操作。