如何在我的Google Chrome扩展程序中将Background.js中的信息传递给autofill.js?

时间:2014-04-07 01:28:52

标签: javascript json google-chrome google-chrome-extension passwords

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

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

Background.js

http://pastebin.com/XiCGXUAx

Autofill.js

http://pastebin.com/C0TiF9yB

TheList.json

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

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

1 个答案:

答案 0 :(得分:0)

要实现此目的,您可以使用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 scriptsHow to store a password as securely in Chrome Extension?