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.
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.
I had to do something similar in one of my extensions and did something very similar to the answer given by @serg but using a HEAD request instead. In theory, a HEAD request should be identical to a GET request but without sending the response body, which in the case of an image or file could be quite a bit of extra data and time waiting.
I also split and shift the header to drop any charsets that might be appended on the content-type.
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:
manifest.json:
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
.A somewhat hackish way (I have no idea if it works always or just sometimes) is to look at the page content. There you will find an element for chrome's PDF viewer. It looks along these lines:
You can check that "type" attribute to see what you are dealing with.
You can evaluate the property
document.contentType
on the current tab. Here is an example onbrowserAction
:This property returns the MIME type that the document is being rendered as, not the
Content-Type
header (no information about the charset).Issuing a new request just to get the MIME type is a bit heavy, and not reliable. For instance, if the currently displayed page is the result of a POST form submission, then issuing a
GET
request will usually not lead to the same page.If you're developing an extension that frequently needs access to this information, use the
chrome.webRequest
API to track the responses. The following demo extension shows the content type upon click of the browser button:Notes:
text/plain
, Chrome falls back to MIME sniffing unless theX-Content-Type-Options: nosniff
is set. In the first case, the detected MIME-type could be anything. In the latter case, the default MIME-type istext/plain
.For completeness, here is a
manifest.json
file that can be used to test the previous code: