如何在 Google Chrome 扩展程序中检测当前选项卡的 MIME 类型? [英] How can I detect the current tab's mime type in a Google Chrome extension?
问题描述
我想查看当前选项卡是否是来自背景页面的 PDF 文件.
I want to see if the current tab is a PDF file from a background page.
我可以在最后检查 .pdf 的网址,但有些 PDF 文件没有.
I can check the url for .pdf at the end but there are some PDF files that don't have that.
推荐答案
您无法使用当前的 Chrome API 来获得它.您可以做的是通过 XHR 再次加载此页面并检查返回内容类型标头.像这样:
You can't get it using current Chrome API afaik. What you can do is load this page again through XHR and check returned content-type header. Something like this:
背景 html:
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if(changeInfo.status == "loading") {
if(checkIfUrlHasPdfExtension(tab.url)) {
//.pdf
pdfDetected(tab);
} else {
var xhr = new XMLHttpRequest();
xhr.open("GET", tab.url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var contentType = xhr.getResponseHeader("Content-Type");
if(checkIfContentTypeIsPdf(contentType)) {
pdfDetected(tab);
}
}
}
xhr.send();
}
}
});
manifest.json:
"permissions": [
"tabs", "http://*/*", "https://*/*"
]
对于 PDF 文件,返回的内容类型应为 application/pdf
.但要记住的是,内容类型标头也可以包含编码:text/html;字符集=UTF-8
.
For PDF files returned content type should be application/pdf
. Something to keep in mind though is that content-type header could contain encoding as well: text/html; charset=UTF-8
.
这篇关于如何在 Google Chrome 扩展程序中检测当前选项卡的 MIME 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!