I want to intercept a request and return a local file as the response using a chrome extension. The user is going to provide the local file path.
Requirements
- I want to do this only through the extension (ideally). No additional installations, no chrome apps, other 3rd party apps should be needed. I'm happy to provide whatever permissions are needed in the manifest, but this will ship, so it can't be in dev-mode / i.e. can't have dev-only APIs.
- The files that the user can select aren't going to be from the extension package, I think the
chrome.runtime.getURL
allows reading from the relative URLs within the package, but it didn't work for exact paths for other files. - I'm aware that by setting up a server in either on localhost, or elsewhere and by redirecting to that URL; this could be achieved, but I'm not interested in that; I'm looking for an out of the box solution which will help me pass local files as responses.
- Also - I'd be happy if there's a workaround - one that I thought was reading the contents of the file that user selected and streaming those contents from memory / or putting them into a temporary location that the
file://
can work with, but couldn't find any way around this yet.
Current state
I'm using the snippet below to handle interception:
// API that I'm using
chrome.webRequest.onBeforeRequest.addListener(function(request){...})
Manifest looks like this:
{
...
"background": {
"scripts": ["background.js"],
"persistent": true
},
"permissions": [
"activeTab",
"tabs",
"http://*/*",
"https://*/*",
"file://*/*",
"webRequest",
"webRequestBlocking"
]
}
I've been able to intercept requests and redirect to other http(s) URLs - this works fine. I'm also receiving the user input for the file path just fine, using <input type="file"/>
for this.
Redirecting the request path to be a file doesn't work though; for obvious security reasons. This is the bit that I'm stuck. Being a bit more descriptive below:
chrome.webRequest.onBeforeRequest.addListener(function(request){
// works fine
if (request.url === 'https://someurl') {
return {redirectUrl : 'https://someotherurl'};
}
// doesn't work - and I'm looking for a solution for this scenario
else if (request.url === 'https://someurl2') {
return {redirectUrl: 'file://somefileondisk' };
}
});
and this doesn't: