如何在Google Chrome扩展程序中检测当前标签的MIME类型? [英] How can I detect the current tab's mime type in a Google Chrome extension?

查看:160
本文介绍了如何在Google Chrome扩展程序中检测当前标签的MIME类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查看当前标签是否来自后台页面的PDF文件。



我可以在最后检查.pdf的网址,但有一些PDF文件没有。

解决方案

您无法使用当前的Chrome API afaik获取它。您可以通过 XHR 再次加载此页面并检查返回内容类型标题。就像这样:

背景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; charset = UTF-8


I want to see if the current tab is a PDF file from a background page.

I can check the url for .pdf at the end but there are some PDF files that don't have that.

解决方案

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:

background 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://*/*"
]

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆