Last active
December 22, 2015 18:18
-
-
Save seanh/85c02c1a0f309abab988 to your computer and use it in GitHub Desktop.
Chrome extension PDF detection with webRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
/** | |
* Get the header from the list of headers for a given name. | |
* @param {Array} headers responseHeaders of webRequest.onHeadersReceived | |
* @return {undefined|{name: string, value: string}} The header, if found. | |
*/ | |
function getHeaderFromHeaders(headers, headerName) { | |
for (var i = 0; i < headers.length; ++i) { | |
var header = headers[i]; | |
if (header.name.toLowerCase() === headerName) { | |
return header; | |
} | |
} | |
} | |
/** | |
* 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(details) { | |
var header = getHeaderFromHeaders(details.responseHeaders, 'content-type'); | |
if (header) { | |
var headerValue = header.value.toLowerCase().split(';', 1)[0].trim(); | |
return (headerValue === 'application/pdf' || | |
headerValue === 'application/octet-stream' && | |
details.url.toLowerCase().indexOf('.pdf') > 0); | |
} | |
} | |
chrome.webRequest.onHeadersReceived.addListener( | |
function callback(details) { | |
if (isPdfFile(details)) { | |
chrome.browserAction.setBadgeText({text: 'PDF'}); | |
} else { | |
chrome.browserAction.setBadgeText({text: 'HTML'}); | |
} | |
}, | |
{urls: ['<all_urls>'], types: ['main_frame']}, | |
['responseHeaders'] | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"manifest_version": 2, | |
"name": "Detecting PDFs with webRequest Demo", | |
"description": "This extension demonstrates a technique for detecting PDFs with Chrome's webRequest API", | |
"version": "1.0", | |
"browser_action": {}, | |
"permissions": [ | |
"webRequest", | |
"<all_urls>" | |
], | |
"background": { | |
"scripts": ["eventPage.js"], | |
"persistent": true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment