Skip to content

Instantly share code, notes, and snippets.

@seanh
Last active December 22, 2015 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/2645a9c857af1402bf63 to your computer and use it in GitHub Desktop.
Save seanh/2645a9c857af1402bf63 to your computer and use it in GitHub Desktop.
Chrome extension PDF detection with GET request from event page
'use strict';
/**
* Check if the request is a PDF file.
* @param {Object} details First argument of the webRequest.onHeadersReceived
* event. The properties "responseHeaders" and "url"
* are read.
* @return {boolean} True if the resource is a PDF file.
*/
function isPdfFile(response, url) {
var header = response.getResponseHeader('content-type');
if (header) {
var headerValue = header.toLowerCase().split(';', 1)[0].trim();
return (headerValue === 'application/pdf' ||
headerValue === 'application/octet-stream' &&
url.toLowerCase().indexOf('.pdf') > 0);
}
}
chrome.browserAction.onClicked.addListener(function callback(tab) {
var oReq = new XMLHttpRequest();
oReq.addEventListener('load', function() {
if (isPdfFile(this, tab.url)) {
chrome.browserAction.setBadgeText({text: 'PDF'});
} else {
chrome.browserAction.setBadgeText({text: 'HTML'});
}
});
oReq.open('GET', tab.url);
oReq.send();
});
{
"manifest_version": 2,
"name": "Detecting PDFs with GET requests Demo",
"description": "This extension demonstrates a technique for detecting PDFs GET requests",
"version": "1.0",
"browser_action": {},
"permissions": [
"<all_urls>"
],
"background": {
"scripts": ["eventPage.js"],
"persistent": false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment