问题
I'm doing a lot of work where I use sublime to code and then need to copy the contents to a web based "editor" that really sucks. I would like the contents of this textbox/editor to be automatically populated with the contents of a text file that I chose.
I don't control the web page that I'm copying code to so can't inject an applet or similar.
What I'm hoping to do is to create a plugin (I'm using chrome) with which I can select an element as target, select a text file on the hard drive (or maybe the contents of a url pointing to localhost if that's easier) and have the plugin scan for changes and update.
Any idea as to how to go about this? Maybe there's already something similar done? I googled but can't seem to find the right terms if there already is something.
回答1:
The easiest way to get the contents of a local file in an extension is probably through XMLHttpRequest
. For example, the following background script gets the content of /etc/passwd
and prints it to the background console:
function pollContent() {
var x = new XMLHttpRequest();
x.open('GET', 'file:///etc/passwd');
x.onload = function() {
// Do something with data, e.g. print to console
console.clear();
console.log(x.responseText);
setTimeout(pollContent, 5000);
};
x.send();
}
pollContent();
In order to use the previous function, you have to declare the file://*/*
permission (or at least file:///etc/passwd
) and enable the "Allow access to file URLs" option for your extension at chrome://extensions/
.
Only the background page can get file://
access. You need to use the message passing API to put the content in a textbox with a content script.
来源:https://stackoverflow.com/questions/21017607/chrome-plugin-reading-text-file-on-hard-drive-and-replacing-textbox-content