To accomplish this task, utilize the Messaging API.
Here is an idea to consider: establish a listener in your background.js
and then insert your content script:
// background.js
chrome.runtime.onMessage.addListener(passwordRequest);
chrome.browserAction.onClicked.addListener(
function (tab) {
// ...
chrome.tabs.executeScript(tab.id, {file: "autofill.js"});
}
);
Subsequently, your content script will initialize and communicate the tab's domain back to the background page:
// autofill.js
chrome.runtime.sendMessage({domain: location.hostname}, fillPassword);
In the background page, handle this message accordingly:
// background.js
// Option 1: synchronous functions for retrieving username/password
function passwordRequest(request, sender, sendResponse) {
var username = getUsername(request.domain);
var password = getPassword(request.domain, username);
if(password !== undefined) {
sendResponse({username: username, password: password});
} else {
sendResponse({error: "No password found for " + request.domain});
}
}
// Option 2: asynchronous storage API
function passwordRequest(request, sender, sendResponse) {
getCredentials(
function(username, password){
if(password !== undefined) {
sendResponse({username: username, password: password});
} else {
sendResponse({error: "No password found for " + request.domain});
}
}
);
return true;
}
In the content script, manage the response using a callback function:
// autofill.js
function fillPassword(response){
if(response.error){
console.warn(response.error);
alert(response.error);
} else {
// autofill with response.username and response.password
// ...
}
}
Consider storing domain-specific IDs for form fields along with credentials for additional functionality.
Note: The above code has not been tested.
Regarding data storage, it would be wise to explore alternatives to fetching local files with XHR, especially for writing to them. View options for local data storage here.
Security must also be a top priority. Understand that there is no foolproof method to securely store sensitive information within a Chrome extension. Consult these discussions for more insight: Password storing in Google Chrome content scripts, How to store a password as securely in Chrome Extension?