如何在我的谷歌浏览器扩展程序中将信息从后台传递.js到自动填充.js

How can I pass information from Background.js to autofill.js in my Google Chrome extension?

本文关键字:js 后台 填充 信息 我的 谷歌浏览器 扩展 程序      更新时间:2023-09-26

我做了一个谷歌浏览器扩展程序,当按下图标时,它会自动填充并提交某些网站(目前为Gmail和Yahoo)的用户名/密码。截至目前,我的密码和用户名在自动填充文件中进行了硬编码。现在我正在尝试将密码/用户名存储在 txt (json) 文件中,背景页面将能够正确读取该 txt 文件(TheList) 并将该文件的内容转换为字符串,我可以轻松调用我需要的变量。现在我需要做的就是找到一种方法,我可以将这些值从后台调用到自动填充上,以便我的用户名/密码值只能存储到 TheList 中,而不是在自动填充中硬编码。有没有办法我可以做到这一点?感谢您抽出宝贵时间阅读本文

这是我对以下文件的代码:

背景.js

http://pastebin.com/XiCGXUAx

自动填充.js

http://pastebin.com/C0TiF9yB

TheList.json

{
"GmailUsername": "USERNAME1",
"GmailPassword": "PASSWORD1",
"YahooUsername": "USERNAME2",
"YahooPassword": "PASSWORD2"
}
抱歉,我

必须通过链接发布我的所有代码,但那是因为它一直说我的代码没有正确缩进,但我发布的所有代码都在灰色框中。感谢您抽出宝贵时间,我真的需要找到一种方法,以便我可以从 TheList 中读取用户名/密码,然后研究之后可以加密该列表的方法。

要实现此目的,您可以使用消息传递 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 获取本地文件,尤其是在要写入它时。一个很好的概述在这里。


另一个需要注意的重要事项是安全性。没有安全/防弹的方法可以在Chrome扩展程序中存储敏感数据。请参阅这些讨论: 密码存储在 Google Chrome 内容脚本中, 如何在 Chrome 扩展程序中安全地存储密码?