问题
I am working on a Chrome extension called Chrome Snippets that will allow you to inject snippets of JavaScript from files but I am having trouble accessing local directories on the user's computer. Anyone have an idea of how to accomplish this?
manifest.json:
{
"name": "Chrome Snippets",
"description": "Run JavaScript on the DOM of any web page from a library of recipes stored on your computer.",
"author": "Adam Fisher",
"version": "1.0",
"manifest_version": 2,
"default_locale": "en",
"permissions": [ "tabs", "webNavigation", "*://*/*", {"fileSystem": ["write", "retainEntries", "directory"]} ],
"app": {
"background": {
"scripts": ["js/background.js"],
"persistent": false
}
},
"icons": {
"16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png"
},
"options_page": "html/options.html",
"homepage_url": "http://adamfisher.me"
}
background.js:
/*
** file: js/background.js
** description: Main functionality of the extension. Checks if a file exists
** for the given host name and loads it.
*/
chrome.webNavigation.onCompleted.addListener(function (details) {
var recipesDirectory = localStorage['Chrome_Snippets_Recipes_Directory'];
var host = "/^(?:ht|f)tps?:\/\/([^/]+)/".exec(details.url); // Get the host part of the URL.
chrome.tabs.executeScript(details.tabId, {
file: ''
});
});

回答1:
You CAN'T make what you want in a single app/extension, that's what Paweł tries to tell you.
Compare Apps APIs and Extensions APIs
Apps can't use tabs
(and in general can't interact with normal browser content), extensions can't use fileSystem
(and in general can't access system resources).
You need to rethink your strategy OR use both an extension and an app that talk to each other.
回答2:
Replace "app"
in the manifest.json file with "background"
:
"background": {
"scripts": ["js/background.js"],
"persistent": false
},
Reference: https://developer.chrome.com/extensions/event_pages
The "app" entry is reserved for Chrome Apps which have different set of API's and permissions.
================================================
Edit
Forgot about what you really asking for.
Chrome extensions can't access user's filesystem. This API is only available for Chrome Apps. So if you need to do it as an extension you can't save files on local file system.
来源:https://stackoverflow.com/questions/27910833/accessing-a-local-directory-from-a-chrome-app