如何将本地存储从popup.js传递到content.js

how to pass localstorage from popup.js to content.js

本文关键字:js content popup 存储      更新时间:2023-09-26

我想将数据从popup.hmtl的本地存储传递到内容脚本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 传输到background.js

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

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

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

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

这正是后台或事件页面对于持久事件侦听器的作用。此外,后台页面与弹出窗口共享localStorage,因此没有问题。


尽管如此,localStorage还有一个更好的替代方案,可以在不发送任何消息的情况下用于弹出和内容脚本:chrome.storage API。