Last active
December 22, 2015 18:19
-
-
Save seanh/27bdaa36aca3b6d6ffa9 to your computer and use it in GitHub Desktop.
Chrome extension PDF detection with GET request from content script
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
/** | |
* 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); | |
} | |
} | |
var oReq = new XMLHttpRequest(); | |
var url = window.location.toString(); | |
oReq.addEventListener('load', function() { | |
if (isPdfFile(this, url)) { | |
chrome.runtime.sendMessage({type: 'PDF'}); | |
} else { | |
chrome.runtime.sendMessage({type: 'HTML'}); | |
} | |
}); | |
oReq.open('GET', url); | |
oReq.send() |
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'; | |
chrome.runtime.onMessage.addListener( | |
function(request, sender, sendResponse) { | |
chrome.browserAction.setBadgeText({text: request.type}); | |
}); |
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 GET requests Demo", | |
"description": "This extension demonstrates a technique for detecting PDFs GET requests", | |
"version": "1.0", | |
"browser_action": {}, | |
"permissions": [ | |
], | |
"background": { | |
"scripts": ["eventPage.js"], | |
"persistent": false | |
}, | |
"content_scripts": [ | |
{ | |
"matches": ["<all_urls>"], | |
"js": ["contentScript.js"] | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment