为此,您可以使用Messaging API。
考虑以下想法:您在 background.js 中设置一个侦听器,然后注入您的内容脚本:
// background.js
chrome.runtime.onMessage.addListener(passwordRequest);
chrome.browserAction.onClicked.addListener(
function (tab) {
// ...
chrome.tabs.executeScript(tab.id, {file: "autofill.js"});
}
);
然后,您的内容脚本会初始化该选项卡的域并将其报告给后台页面:
// autofill.js
chrome.runtime.sendMessage({domain: location.hostname}, fillPassword);
返回后台页面,您处理该消息:
// background.js
// Option 1: you have synchronous functions to get 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: your storage API is asynchronous
function passwordRequest(request, sender, sendResponse) {
getCredentials( // Your async credentials retrieval
function(username, password){ // Callback
if(password !== undefined) {
sendResponse({username: username, password: password});
} else {
sendResponse({error: "No password found for " + request.domain});
}
}
);
return true; // Required for asynchronous sendResponse
}
回到内容脚本中,您在回调中处理响应:
// autofill.js
function fillPassword(response){
if(response.error){
console.warn(response.error);
alert(response.error);
} else {
// autofill with response.username and response.password
// ...
}
}
为了获得额外的好处,您可以为表单字段存储特定于域的 ID,并将它们与凭据一起传递。
注意:上面的代码我没有测试过。
在相关说明中,您应该考虑使用其他可用选项来存储本地数据,而不是使用 XHR 获取本地文件,尤其是在您想写入时。一个很好的概述是here。
另一个需要注意的重要事项是安全性。 没有安全/防弹的方法可以在 Chrome 扩展程序中存储敏感数据。 请参阅这些讨论:Password storing in Google Chrome content scripts、How to store a password as securely in Chrome Extension?