Chrome extensions . Read or write files from the local hard disk.
Chrome extensions cannot directly read or write files from the local hard disk (HDD/SSD) for security reasons. However, there are workarounds depending on your needs.
๐ What Chrome Extensions Can Do
Read user-selected files:
You can use the
<input type="file">element or the File API to allow users to select files manually.Example: User selects a file, and your extension reads its contents.
Write files using downloads API:
You can create a file and let the user download it using
chrome.downloads.download().Example: Save extracted job titles to a
.txtor.jsonfile.
๐ซ What Chrome Extensions CANNOT Do
Directly access the file system like a regular app.
- Extensions cannot read/write arbitrary files from
C:\,/home/, etc.
- Extensions cannot read/write arbitrary files from
Modify files on disk automatically.
- You cannot edit an existing file on the HDD without user interaction.
โ Workarounds
Hereโs how you can handle file operations:
1๏ธโฃ Read a File (User Selects a File)
document.getElementById("fileInput").addEventListener("change", function(event) {
let file = event.target.files[0]; // Get the selected file
let reader = new FileReader();
reader.onload = function(event) {
console.log("File content:", event.target.result); // Process file data
};
reader.readAsText(file); // Read file as text
});
๐น Requires <input type="file" id="fileInput"> in your popup.
2๏ธโฃ Write and Download a File
function downloadFile(content, filename) {
let blob = new Blob([content], { type: "text/plain" });
let url = URL.createObjectURL(blob);
chrome.downloads.download({
url: url,
filename: filename,
saveAs: true // Prompt user where to save
});
}
// Example: Save extracted job titles
downloadFile("Sviluppatore\nPython Developer", "job_titles.txt");
๐น Uses chrome.downloads.download() to create and save files.
3๏ธโฃ Use Native Messaging (Advanced)
๐น If you really need full disk access, you must:
Create a separate external program (Python, Node.js, etc.).
Use Native Messaging API to communicate with it.
The external program can read/write files freely.
๐ Example: Chrome Extension sends job titles โ Python script saves to C:\data\jobs.txt.
๐ Conclusion
๐ด No direct HDD access.
๐ข Yes: Read user-selected files.
๐ข Yes: Save new files via
chrome.downloads.๐ก Advanced: Use Native Messaging for full access.