Javascript 如何在我的Google Chrome扩展中将信息从Background.js传递到autofill.js?
我做了一个Google Chrome扩展,当按下图标时,自动填充并提交某些网站的用户名/密码。到目前为止,我的密码和用户名都硬编码在自动填充文件中。现在,我试图将密码/用户名存储在txt json文件中,以便后台页面能够正确读取该txt文件列表,并将该文件的内容转换为字符串,我可以轻松调用所需的变量。现在,我需要做的就是找到一种方法,从后台将这些值调用到autofill,这样我的用户名/密码值就可以只存储到列表中,而不用在autofill中硬编码。有没有什么我可以做的?感谢您抽出时间阅读此文章 以下是我对以下文件的代码: Background.js Autofill.js TheList.json 很抱歉,我不得不通过链接发布我的所有代码,但那是因为它一直说我的代码没有正确缩进,但我发布的所有代码都在灰色框中。Javascript 如何在我的Google Chrome扩展中将信息从Background.js传递到autofill.js?,javascript,json,google-chrome,google-chrome-extension,passwords,Javascript,Json,Google Chrome,Google Chrome Extension,Passwords,我做了一个Google Chrome扩展,当按下图标时,自动填充并提交某些网站的用户名/密码。到目前为止,我的密码和用户名都硬编码在自动填充文件中。现在,我试图将密码/用户名存储在txt json文件中,以便后台页面能够正确读取该txt文件列表,并将该文件的内容转换为字符串,我可以轻松调用所需的变量。现在,我需要做的就是找到一种方法,从后台将这些值调用到autofill,这样我的用户名/密码值就可以只存储到列表中,而不用在autofill中硬编码。有没有什么我可以做的?感谢您抽出时间阅读此文章
感谢您抽出时间,我真的需要找到一种方法,这样我就可以从列表中读取用户名/密码,然后研究如何在之后对该列表进行加密。要实现这一点,您可以使用 考虑以下想法:在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来获取本地文件,而应该考虑其他可用的选项来存储本地数据,特别是如果您想写入本地数据时。一个好的概述是
另一个需要注意的重要事项是安全。在Chrome扩展中没有安全/防弹的方式来存储敏感数据。见这些讨论:// autofill.js
function fillPassword(response){
if(response.error){
console.warn(response.error);
alert(response.error);
} else {
// autofill with response.username and response.password
// ...
}
}