我正在尝试使用此background.js获取cookie值
var myUrl = "https://cookiedomain.com/";
chrome.cookies.get({url: myUrl, name: 'email'}, function(cookie) {
var email = cookie.value;
chrome.runtime.sendMessage({ data: email });
});
chrome.cookies.get({url: myUrl, name: 'password'}, function(cookie) {
var password = cookie.value;
chrome.runtime.sendMessage({ data: password });
});
并在content.js中获取电子邮件和密码作为变量
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
var email = request.email;
var password = request.password;
});
....
document.getElementById('id').value = email;
document.getElementById('id1').value = password ;
但似乎没有用,有人可以帮我吗?
感谢所有人。
答案 0 :(得分:1)
您的代码中存在几个问题:chrome。选项卡 .sendMessage应该与一个选项卡ID一起使用,两个document.getElementById行应该位于onMessage回调中,而您的背景脚本是发送一个内部具有data
属性的对象,但内容脚本原本期望email
和password
。
有一个更简单的方法:逆向流程,让内容脚本向后台脚本发出请求,这将获取两个cookie并将它们发送回单个响应中。
后台脚本:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.topic === 'getAuth') {
chrome.cookies.get({url: msg.url, name: 'email'}, ({value: email}) => {
chrome.cookies.get({url: msg.url, name: 'password'}, ({value: password}) => {
sendResponse({email, password});
});
});
// keep sendResponse channel open
return true;
}
});
内容脚本:
chrome.runtime.sendMessage({
topic: 'getAuth',
url: location.href,
}, ({email, password}) => {
document.getElementById('id').value = email;
document.getElementById('id1').value = password;
});