如何将localstorage从popup.js传递给content.js

时间:2014-11-05 11:15:39

标签: javascript google-chrome-extension content-script message-passing

我想将popup.hmtl的localstorage中的数据传递给内容脚本content.js 我使用popup.html接收用户名和密码并将其存储在本地存储中。现在我想在执行之前将数据传输到内容脚本。

**popup.html**
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" async src="popup.js"></script>
</head>
<body>

<table>
<tr>
<td>
Username:
<td><input id="u1" type="text" name="uname">
</tr>
<tr>
<td>
Password:
<td><input id="u2" type="password" name="pass">
</tr>
<tr>
<td>
<td>
<input id="clickme" type="button" value="save" />
</tr>

</table>

<div id="result"></div>
<div id="result2"></div>

</body>
</html>

popup.js

document.getElementById('clickme').onclick=myfunction;
var sname = localStorage.getItem("username1");
var spass=localStorage.getItem("password1");
document.getElementById("result").innerHTML = localStorage.getItem("username1");
document.getElementById("result2").innerHTML=localStorage.getItem("password1");

function myfunction(){

// Check browser support
if (typeof(Storage) != "undefined") {

    var uname="bhuwan";
    var username=document.getElementById("u1").value;
    var password=document.getElementById("u2").value;

    // Store
    localStorage.setItem("username1", username);
    localStorage.setItem("password1",password);
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("username1");
    document.getElementById("result2").innerHTML=localStorage.getItem("password1");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

content.js

{
var pid="";
var cid="";


chrome.runtime.sendMessage({method: "getLocalStorage",key="username"}, function(response) {
  var cid = response.data;

});
chrome.runtime.sendMessage({method: "getLocalStorage"},key="password" function(response) {
  var pid = response.data;

});


}

我找到了答案:

将以下代码从popup.js

转移到背景.js
 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        if (request.method == "getLocalStorage")
          sendResponse({data: localStorage[request.key]});
        else
          sendResponse({}); // snub them.
    });

因为只有在点击图标时popup.js才处于活动状态。所以没有消息传递。

1 个答案:

答案 0 :(得分:2)

您正尝试通过向弹出页面发送消息来检索数据。

这个问题:弹出页面只有在显示时才存在。当它关闭时,它被销毁,你的onMessage监听器不存在,请求失败。

这正是backgroundevent pages的用途 - 持久事件侦听器。此外,后台页面与弹出窗口共享localStorage,因此没有任何问题。


所有这一切,除了localStorage之外,还有一个更好的替代方法,可以在没有任何消息的情况下弹出和内容脚本:chrome.storage API